按键和值对地图排序

fer*_*dyh 4 java sorting map

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

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

任何人都有关于如何有效实现这一目标的建议?我一直在看人们使用TreeMap对键进行排序,但我也需要值.

或者,我们欢迎任何其他方法对键和值进行排序.

hd4*_*d42 6

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;
    }
}
Run Code Online (Sandbox Code Playgroud)