Java 8 – Sort Map by Value, by Key – Sort Map Custom Object by CompareTo – Descending & Ascending Order

java-8-sort-map-by-keys-by-values-custom-objects-descending-ascending---feature-image

In the tutorial, we show how to sort Java Map by Values, by Keys, and Custom Objects with Descending & Ascending order in Java 8.

I. How to Sort Map by Values?

– We use .stream().sorted(Map.Entry.comparingByValue()) to sort map by value:

Note: using a LinkedHashMap to collect results. Because, by default Collectors.toMap returns a new HashMap, but HashMap doesn’t guarantee iteration order, while LinkedHashMap does.

Reversed Order

How to reverse order?
-> We use comparingByValue().reversed().

II. How to Sort Java Map by Keys?

– We do the same above ways but using .sorted((Map.Entry.comparingByKey())):

Reversed Order

– For reversed order, we use .sorted((Map.Entry.comparingByKey().reversed()))

III. Sort Map Custom Objects by CompareTo function

– To sort a Map with Custom Objects, we use compareTo function:

Reversed Order

– For descending order, we re-define the compareTo function in Customer class:

-> Full Example:



By grokonez | February 11, 2019.


Related Posts


    Got Something To Say:

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

    *