How to Sort a HashMap In Java 8

  • Post last modified:July 16, 2022
  • Reading time:2 mins read

How many options do we have to sort a Hashmap in Java 8?

Introduction

  • As a developer, we often need some data structure to store than data and then perform some operations such as sort or filter on that data so that we can satisfy the business requirement.
  • In this article, we will explore how can we sort HashMap in Java
  • Our Map data structure consists of a news article as value and key as the tag of the article. We would sort the map based on tags.

Java Collections Class

  • Java collections class expects list input for its sorting method. 
    Hence we need to provide a list created from the map.
  • Our output would be sorted based on tags.
  • We can further modify the code using Comparator.comparing and using method reference for sorting using the key.

Java 8 Streams API

  • We can use the sorted method on the stream of the entry set and provide sorting logic as a lambda function. Here we are sorting based on the tags of the news articles.
  • Our output would be sorted based on tags in ascending order of tags
  • We can sort the map using value as well. newsMap has news object as value & we will sort using the title of the article.
  • Below is our sorted output based on the values of the map.
  • We can also reverse the order by value
  • Output is based on reverse order of title of the news

Conclusion

  • We can sort the map using the Collections class sort method. A sort method only accepts lists, we need to convert a hashmap into an entry set and create a list of entry set from it. Then we can pass out list and comparator logic to sort the data either based on key or value.
  • We can also use Java Stream API, convert it to an entry set and perform sort operations by providing comparator logic.
  • Both the options look fine to sort the hashmap, although lambda and method reference can be used with both the approach to avoid boilerplate code.

Leave a Reply