小编典典

按键和值对地图排序

java

我想在键和值上对地图进行排序。首先是关键,然后是价值。例如,这应该是结果;

1,2 1,3 2,1 2,2

有人对如何有效地实现这一目标有建议吗?我一直在看到人们使用TreeMap对键进行排序,但是我也需要值。

或者欢迎使用其他对键和值进行排序的方法。


阅读 189

收藏
2020-11-19

共1个答案

小编典典

import java.util.SortedSet;
import java.util.TreeSet;

public class SortMapOnKeyAndValue {

    public static void main(String[] args) {
        SortedSet<KeyValuePair> sortedSet = new TreeSet<KeyValuePair>();
        sortedSet.add(new KeyValuePair(1, 2));
        sortedSet.add(new KeyValuePair(2, 2));
        sortedSet.add(new KeyValuePair(1, 3));
        sortedSet.add(new KeyValuePair(2, 1));

        for (KeyValuePair keyValuePair : sortedSet) {
            System.out.println(keyValuePair.key+","+keyValuePair.value);
        }
    }
}
class KeyValuePair implements Comparable<KeyValuePair>{
    int key, value;

    public KeyValuePair(int key, int value) {
        super();
        this.key = key;
        this.value = value;
    }

    public int compareTo(KeyValuePair o) {
        return key==o.key?value-o.value:key-o.key;
    }
}
2020-11-19