I think you could use the four argument toMap
method that returns a collector. Assuming the getScore
method returns an Integer
(or you can stay with String
if you want but it will be less usable I think) :
//supplier of TreeMap with your custom comparator
Supplier<TreeMap<Integer, String>> myMapSupplier = () -> new TreeMap<>(Comparator.reverseOrder());
Map<Integer, String> result = myMap.values()
.stream()
.collect(Collectors.toMap(Person::getScore, Person::getName, (s, s2) -> s, myMapSupplier));
The last element is the supplier of the Map
. As documentation states :
mapSupplier - a function which returns a new, empty Map
into which the results will be inserted
So you can still have a TreeMap
with a custom Comparator
in a single call.