Hashmap is a hashing data structure that uses hashing technique to store key-value pairs, such that keys of no 2 pairs are equal. In this article, we shall look at different techniques of how to sort the entries of a hashmap in Java.
This article shall cover:
- Sorting Java hashmap using a TreeMap.
- Sorting Java hashmap using an ArrayList.
- Sorting Java hashmap using Java 8 lambda.
- Sorting Java hashmap using Java stream.
This article shall not deal with:
- Hashmap data structure internals.
- Any other unrelated Java concepts.
TreeMap in Java is a container based on Red-black tees that stores items in it in a sorted fashion. In the code block ahead, as we add the key-value pairs from HashMap to a TreeMap, the TreeMap naturally inserts the pairs in itself in sorted order by keys.
We can also construct the TreeMap and pass the HashMap object as an argument to the constructor. This way we need not explicitly call “puAll()”.
In this method, we first store all the entries of the hashmap in an ArrayList container and then sort the ArrayList object.
Using Java 8 lambda expressions
In this method the way we sort changes as it will now be using a lambda expression.
Using Java 8 stream
In this method, we call “stream()” which returns a stream of entrySet followed. This is followed by the usage of lambda expression inside the “sorted()” function to sort the stream. Finally, we use the “toMap()” function to convert it into a map. We’ll have to use the LinkedHashMap::new method reference in the toMap call for retaining the map’s sorted order.