我想根据键和值对 Map 进行排序。首先是关键,然后是值(value)。 例如,这应该是结果;
1,2
1,3
2,1
2,2
有人对如何有效地实现这一点有什么建议吗?我一直看到人们使用 TreeMap 对键进行排序,但我也需要值。
或者欢迎使用任何其他方法对键和值对进行排序。
最佳答案
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;
}
}
关于java - 根据键和值对映射进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6546782/