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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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