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 Strings as keys, and Integers as values. Most of the time, you’ll encounter Integers or Strings as keys, and custom objects, Strings or Integers as values. We’ll want to sort this HashMap, based on the String keys.

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.

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

How to Sort a HashMap by Key in Java
1.50 GEEK