Skip to content

Java Sort LinkedHashMap By Keys Example

This example shows how to sort LinkedHashMap by keys in Java. This example also shows how to sort LinkedHashMap using the TreeMap and a custom Comparator.

How to sort LinkedHashMap by key in Java?

The LinkedHashMap entries can be sorted by keys using the TreeMap class. The TreeMap automatically inserts the entries sorted by the key.

To do that, we will convert the LinkedHashMap to a TreeMap object using the TreeMap constructor that accepts a Map argument as given below.

Output

If you do not want the sorted entries back in the original LinkedHashMap object, you do not need to clear it and add all sorted entries back to the LinkedHashMap object.

How to sort LinkedHashMap having custom class objects as keys?

Let’s try to sort a linked hash map having custom class objects as keys using the same approach.

Output

As you can see from the output above, the TreeMap throws a ClassCastException exception.

If the LinkedHashMap keys are objects of a custom class, then the custom class must implement the Comparable interface and define the compareTo method or a custom Comparator object must be specified in the TreeMap constructor.

LinkedHashMap sort by keys using the Comparable interface

Let’s implement the Comparable interface in our Student class and define the compareTo method.

Output

As you can see from the output, the LinkedHashMap keys are sorted by the Student class in ascending order. If you want to sort the keys in descending order, replace the compareTo method in the above code with the code given below.

Output

LinkedHashMap sort by keys using the Comparator interface

Another option is to create a custom Comparator and pass the object of that to the TreeMap constructor as given below.

Output

This example is a part of the LinkedHashMap in Java Tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedHashMap

About the author

Leave a Reply

Your email address will not be published.