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

198,008

Solution 1

You aren't going to be able to do this from the HashMap class alone.

I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> 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<String, String> reversedMap = new TreeMap<String, String>(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.

Solution 2

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

Map<String, String> map = getMyMap();
List<String> keys = new ArrayList<String>(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 <K, V extends Comparable<? super V>>
        Comparator<K> mapValueComparator(final Map<K, V> map) {
    return new Comparator<K>() {
        public int compare(K key1, K key2) {
            return map.get(key1).compareTo(map.get(key2));
        }
    };
}

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

Solution 3

It's time to add some lambdas:

codes.entrySet()
    .stream()
    .sorted(Comparator.comparing(Map.Entry::getValue))
    .forEach(System.out::println);

Solution 4

you just need to use:

 Map<>.toString().replace("]","\n");

and replaces the ending square bracket of each key=value set with a new line.

Solution 5

the for loop of for(Map.Entry entry: codes.entrySet()) didn't work for me. Used Iterator instead.

Iterator<Map.Entry<String, String>> i = codes.entrySet().iterator(); 
while(i.hasNext()){
    String key = i.next().getKey();
    System.out.println(key+", "+codes.get(key));
}
Share:
198,008
Admin
Author by

Admin

Updated on November 03, 2020

Comments

  • Admin
    Admin over 3 years

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

    But the order when I print it out is seemingly random.

    What's the best way to print it out in ascending value order?

    Map<String, String> codes = new HashMap<String, String>();
    
    codes.put("A1", "Aania");
    codes.put("X1", "Abatha");
    codes.put("C1", "Acathan");
    codes.put("S1", "Adreenas");
    

    In other words, the example above should print out as this:

    A1, Aania
    X1, Abatha
    C1, Acathan
    S1, Adreenas