Hi All,

Greeting of the day!

Today we will see how we can sort HashMap by both key & value. Also, we will explore how we can sort HashMap using java 8.

  • To sort HashMap by key we can simply put HashMap data in TreeMap.
  • To sort HashMap by the value we have to follow 3 steps
    • Create LinkedList from Map.
    • Sort List by value using Comparator.
    • Create Map from the sorted list.  

So let's start

Below will be our output.

Now let's see how to sort HashMap by key using java 8

Now let's see how to sort HashMap by value using java 8

Below is a complete program for reference.


Below is output

Let me know if you have any questions.

Also, you can refer below useful post






For spring refer to Spring Tutorial

Thank you
Happy Learning!