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

前端 未结 13 1553
春和景丽
春和景丽 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 aren't going to be able to do this from the HashMap class alone.

    I would take the Map codes, construct a reverse map of TreeMap reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.

    Map reversedMap = new TreeMap(codes);
    
    //then you just access the reversedMap however you like...
    for (Map.Entry entry : reversedMap.entrySet()) {
        System.out.println(entry.getKey() + ", " + entry.getValue());
    }
    

    There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.

提交回复
热议问题