黑马程序员_Map集合中按value值进行排序

来源:互联网 发布:php popen 编辑:程序博客网 时间:2024/04/28 10:27
public class CountString {    public static void main(String[] args) {        Map<String, Integer> maps = new HashMap<String, Integer>();        maps.put("abc",2);        maps.put("xyz",9);        maps.put("jpg",7);        List<Map.Entry<String, Integer>> entryLists = new ArrayList<Map.Entry<String, Integer>>(maps.entrySet());        Collections.sort(entryLists, new EntryComparator());         // System.out.println(entryLists);        for (Map.Entry<String, Integer> entry : entryLists) {                   System.out.print(entry.getKey() + ":" + entry.getValue()+" ");        }   }   public static class EntryComparator implements Comparator<Map.Entry<String, Integer>> {// value列表顺序的比较器      public int compare(Map.Entry<String, Integer> map1,  Map.Entry<String, Integer> map2) {// 重写compare方法          return map1.getValue() - map2.getValue(); // 升序排列           // return map2.getValue() - map1.getValue();// 降序排列        }    }}

排序后,输出结果为:abc:2 xyz:7 jpg:9

0 0