sort value of a map by comparator with java streams api

nimo23 :

I have a Map and want to sort the values by a Comparator putting the result into a LinkedHashMap.

Map<String, User> sorted = test.getUsers()
                .entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(SORT_BY_NAME))
                .collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()),
                        LinkedHashMap::putAll);
test.setUsers(sorted);

All works, however, I wonder if this can be simplified.

Actually I create a new Map and put that new Map into the setUsers(). Can I change the stream directly without creating a new LinkedHashMap?

With Collections.sort(Comparator), the list is directly sorted. However, Collections.sort does not work with Maps.

Leo Aso :

You cannot perform in-place sorting on a collection that does not support array-style indexing, so for maps it is out of the question (except you use something like selection sort on a LinkedHashMap, but that would be a bad idea). Creating a new map is unavoidable. You can still simplify it though, by following shmosel's answer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309351&siteId=1