Java Sorting Map by key

March 9, 2018
To have a sorted map by key in Java you can use the TreeMap. It guarantees the natural order. You can use it like this:
For more details read the following paragraphs.

TreeMap with the natural order

This type of a Map stores the elements in the natural order. If you just want to sort a variable map, you can use the constructor of the TreeMap: new TreeMap(mapas in the following example:

The result of executing this code is:


Complex classes as a key

If the key of a map is a complex class, to sort a map using TreeMap you need to implement in the class the Comparable interface. Let’s assume that we have a class Person containing the firstName (String), lastName (String) and age (Integer). If you want objects of this class to be sorted by age, the class may look like this one:
To test if this works correctly, we may execute the code below

After executing the code, the result is:

As you can see, people were sorted correctly by age.

Click here to add a comment

Leave a comment:

Privacy Preference Center