How print out the contents of a HashMap in ascending order based on its values?

前端 未结 13 1529
春和景丽
春和景丽 2020-12-24 11:58

I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 12:40

    You can use a list of the entry set rather than the key set and it is a more natural choice given you are sorting based on the value. This avoids a lot of unneeded lookups in the sorting and printing of the entries.

    Map map = ...
    List> listOfEntries = new ArrayList>(map.entrySet());
    Collections.sort(listOfEntries, new SortByValueComparator());
    for(Map.Entry entry: listOfEntries)
       System.out.println(entry);
    
    static class SortByValueComparator implements Comparator> {
       public int compareTo(Map.Entry e1, Map.Entry e2) {
           return e1.getValue().compateTo(e2.getValue());
       }
    }
    

提交回复
热议问题