In this tutorial, we’ll take a look at how to sort a HashMap by value in Java.

Let’s go ahead and create a simple HashMap:

Map<String, Integer> unsortedMap = new HashMap();

unsortedMap.put("John", 21);
unsortedMap.put("Maria", 34);
unsortedMap.put("Mark", 31);
unsortedMap.put("Sydney", 24);

unsortedMap.entrySet().forEach(System.out::println);

We’ve got Strings as keys, and Integers as values. And we’d like to sort this map based on the values.

HashMapdon’t guarantee to maintain the order of its elements in any case. The order can change through time, and they most definitely won’t be printed back in the order of insertion:

John=21
Mark=31
Maria=34
Sydney=24

If you re-run this program, it’ll keep this order, since HashMaps order their elements into bins, based on the hash value of the keys. When printing values from a HashMap, its contents are printed sequentially, so the results will stay the same if we re-run the program multiple times.

Note: TreeMap extends the SortedMap interface, unlike the HashMap implementation. TreeMaps are meant to be the sorted counterpart, however, TreeMaponly sort by keys, given a comparator.

#java #how to sort a hashmap by value in java #hashmap #value in java #sort

How to Sort a HashMap by Value in Java
1.10 GEEK