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 String
s as keys, and Integer
s as values. And we’d like to sort this map based on the values.
HashMap
s don’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 HashMap
s 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. TreeMap
s are meant to be the sorted counterpart, however, TreeMap
s only sort by keys, given a comparator.
#java #how to sort a hashmap by value in java #hashmap #value in java #sort