map按key和value排序

来源:互联网 发布:armageddon软件 编辑:程序博客网 时间:2024/05/22 13:14

#map集合按照key和value排序

##按value排序

利用集合中的Entry封装,然后利用内部函数描述比较过程,这里有两种方式,可以发现其中的o1和o2表示map中的值,o1其实是偏大的那一个,然后返回的时候其实是将较大的放在后面。

Map<String, Integer> map = new TreeMap<String, Integer>();map.put("b", 1);map.put("a", 2);map.put("c", 3);System.out.println("排序前:" + map);List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());/** for(int i = 0;i < list.size();i ++){ String key = list.get(i).toString(); System.out.println(key); }*/Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {public int compare(Map.Entry<String, Integer> o1,Map.Entry<String, Integer> o2) {/*if(o1.getValue() > o2.getValue()){//按value顺序排列return 1;}else if(o1.getValue() < o2.getValue()){return -1;}return 0;*///return o1.getValue() - o2.getValue();//顺序按value排列}});System.out.println("排序后:");for (int i = 0; i < list.size(); i++) {String key = list.get(i).toString();System.out.println(key);}}


##按key排序

和上面一样,只不过在内部类中需要有一个compareTo函数

只要将上面的return o1.getValue() - o2.getValue();改为return (01.getKey().toString().compareTo(02.getKey().toString()));

0 0