HashMap is a class in Java that implements Map interface and holds values based on an unique key.As we know HashMap is an unsorted and unordered Map. Hence, requirements come where we need to sort the HashMap either by its key or values.In this post, we will take a look into how to sort a HashMap by key as well as by value.
As we know there is an implementation of NavigableMap interface, known as TreeMap which also holds a key value pair but maintains the key sorted(natural order) in ascending order by default.Hence, to sort a HashMap by it's key it is only required to convert existing HashMap into a TreeMap.Apart from this, we can also define our custom sort order by implementing Comparable or Comparator Interface to sort a TreeMap.
First, let us take a look into how to sort a HashMap by it's key in natural order.
Above code snippet will sort the Map by key in ascending order and it is a natural sorting.Now to sort it in descending order or to sort the map with custom object keys, we need to implement Comparator as below:
Sorting a Hashmap by values is little tricky as TreeMap is unable to sort the Map by it's values.To sort a HashMap by it's values, we need to convert the existing Map into a List and then sort this list by using Comparator interface and then again put this sorted list back to a Map.
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
©2016, DevGlan. All Rights Reserved.
Contact us: email@example.com