How to Sort HashMap in Java by Values

In my previous post we have learnt How to Sort HashMap in Java by Keys, in this article we will learn to sort HashMap values. We will be using the below three approaches.

  1. Implementing the Comparator Interface along with TreeMap Collection
  2. Implementing a separate class implementing Comparator Interface
  3. Using Collections.sort() method

[Read more…]

How to Sort HashMap in Java by Keys

We all know that HashMap will not save key-value pairs in any sort of order neither preserve the insertion order. In this tutorial we will learn how to sort a HashMap based on Keys. We will be using two approaches.

  1. TreeMap Collection class (Which has in-built support for sorting the elements using Comparable and Comparator  Interface)
  2. Implementing the Comparator Interface
  3. Using Collections.sort() method

[Read more…]