3

I am new Java 8 and want to sort a Map based on Key and then sort each list within values.

I tried to look for a Java 8 way to sort Keys and also value. HashMap> map

map.entrySet().stream().sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(Map.Entry::getKey, 
        Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

I am able to sort the Map and I can collect each values within map to sort but is their a way we can do in java 8 and can both be combined.

2
  • Use a groupingBy with a downstream Collector. Commented Aug 11, 2018 at 22:04
  • Maybe, you could use a TreeMap instead of a HashMap. TreeMaps order by key as a feature of the implementation. Commented Aug 11, 2018 at 23:12

1 Answer 1

4

To sort by key, you could use a TreeMap. To sort each list in the values, you could iterate over the values of the map by using the Map.values().forEach() methods and then sort each list by using List.sort. Putting it all together:

Map<Integer, List<Integer>> sortedByKey = new TreeMap<>(yourMap);

sortedByKey.values().forEach(list -> list.sort(null)); // null: natural order

This sorts each list in-place, meaning that the original lists are mutated.


If instead you want to create not only a new map, but also new lists for each value, you could do it as follows:

Map<Integer, List<Integer>> sortedByKey = new TreeMap<>(yourMap);

sortedByKey.replaceAll((k, originalList) -> { 
    List<Integer> newList = new ArrayList<>(originalList);
    newList.sort(null); // null: natural order
    return newList;
});

EDIT:

As suggested in the comments, you might want to change:

sortedByKey.values().forEach(list -> list.sort(null));

By either:

sortedByKey.values().forEach(Collections::sort);

Or:

sortedByKey.values().forEach(list -> list.sort(Comparator.naturalOrder()));

Either one of the two options above is much more expressive and shows the developer's intention in a better way than using null as the comparator argument to the List.sort method.

Same considerations apply for the approach in which the lists are not modified in-place.

Sign up to request clarification or add additional context in comments.

1 Comment

just a little cleaner with reference, you can use sortedByKey.values().forEach(Collections::sort); for natural order sorting of the list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.