Reputation: 5680
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.
Upvotes: 1
Views: 91
Reputation: 12463
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.
Upvotes: 2
Reputation: 50716
Why not use Collectors.toMap()
?
.collect(Collectors.toMap(
Entry::getKey,
Entry::getValue,
(a, b) -> { throw new AssertionError("impossible"); },
LinkedHashMap::new));
Upvotes: 3