Java Sort LinkedHashMap by Values Example

This example shows how to sort LinkedHashMap by values in Java. This example also shows how to sort LinkedHashMap by values using a custom Comparator.

How to sort LinkedHashMap by value in Java?

How to get sorted values from the LinkedHashMap object?

If you want only sorted values from the LinkedHashMap, you can get all the values from the LinkedHashMap using the values method, convert it to a List and then sort that List object as given below.

Output

The sort method of the Collections class sorts the List elements according to their natural order, for the Integer type that is ascending order. That is why we need to provide the custom comparator object to order the List with LinkedHashMap values in descending order.

How to sort key-value mappings using the values of LinkedHashMap?

Using the above given code, we only get the sorted values of the map object. What if you want to get all key-value mappings or entries sorted by the values?

Well, in that case, we can get all the entries from the LinkedHashMap using the entrySet method, convert it to a List and then sort the values List using a custom comparator as given below.

Output

For sorting the entries in descending order, change the sort method as given below.

Output

How to sort LinkedHashMap by values having custom class objects?

All the above examples used the objects of an Integer class as a value of the map that has implemented the Comparable interface.

If the LinkedHashMap values are objects of a custom class, that the custom class must implement the Comparable interface for the sort method to work, or you must provide the custom comparator while using the sort method.

Using the Comparable interface:

Output

Using the Comparator interface:

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 *

Online Shopping