In this tutorial, we’ll take a look at how to sort a HashMap by key 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. Most of the time, you’ll encounter Integer
s or String
s as keys, and custom objects, String
s or Integer
s as values. We’ll want to sort this HashMap
, based on the String
keys.
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.
#java #how to sort a hashmap by key in java #hashmap #key in java #sort #sort a hashmap by key in java