Sort a Map in Java Example

Posted on Updated on

A map is an data structure class that stores associations between keys and values which are widely used in java programming language. As map stores key-value pair, we can can sort map by two ways.

  1. Sort by keys
  2. Sort by values

Let us see example to sort map in both ways.

1) Sort a Map by keys

There are several ways to sort a map in java. I would like to use TreeMap class to sort a unsorted map.


In above example we have sorted a map which contains Integer as key and String as value. What if I have vice versa, String as key and Integer as value? The answer of this question is same use TreeMap class to sort the unsorted map.

Here is the example to sort unsorted map with String as key and Integer as value.


2) Sort a Map by values


Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.