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

前端 未结 13 1511
春和景丽
春和景丽 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:36

    You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.

    Map map = getMyMap();
    List keys = new ArrayList(map.keySet());
    Collections.sort(keys, someComparator);
    for (String key: keys) {
        System.out.println(key + ": " + map.get(key));
    }
    

    As for what to use for someComparator, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:

    public static >
            Comparator mapValueComparator(final Map map) {
        return new Comparator() {
            public int compare(K key1, K key2) {
                return map.get(key1).compareTo(map.get(key2));
            }
        };
    }
    
    public static 
            Comparator mapValueComparator(final Map map,
                                             final Comparator comparator) {
        return new Comparator() {
            public int compare(K key1, K key2) {
                return comparator.compare(map.get(key1), map.get(key2));
            }
        };
    }
    

提交回复
热议问题