map 排序


用于map的值排序的方法,修改SortedSet 的方法即可,代码见下方:


public class MapHandle {


//重写compare方法

static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map) {

SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(

new Comparator<Map.Entry<K, V>>() {

@Override

public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {

扫描二维码关注公众号,回复: 773282 查看本文章

int res = e2.getValue().compareTo(e1.getValue());  //key排序,调换e2与e1的位置即可

return res != 0 ? res : 1; // Special fix to preserve

// items with equal values

}

});

sortedEntries.addAll(map.entrySet());

return sortedEntries;

}


public static void main(String[] args) {

Map<String, Integer> map = new TreeMap<String, Integer>();

map.put("苹果", 2);

map.put("梨子", 1);

map.put("香蕉", 3);

map.put("橘子", 3);

map.put("菠萝", 3);

map.put("西瓜", 3);

map.put("桃子", 3);

for (String string : map.keySet()) {

System.out.print(string + ":");

System.out.println(map.get(string));

}

System.out.println(map);    //原本的输出结果

System.out.println(entriesSortedByValues(map));    //调用后的结果

}


}


输出结果:

桃子:3

梨子:1

橘子:3

苹果:2

菠萝:3

西瓜:3

香蕉:3

{桃子=3, 梨子=1, 橘子=3, 苹果=2, 菠萝=3, 西瓜=3, 香蕉=3}

[桃子=3, 橘子=3, 菠萝=3, 西瓜=3, 香蕉=3, 苹果=2, 梨子=1]

猜你喜欢

转载自yrandy.iteye.com/blog/1687787