Skip to content

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

Leave a Reply

Your email address will not be published.