This is a follow-up of How to get the count of keys for values in a hash map using lambda. I have a HashMap
and I want to find the number of keys for each value
You could have the following:
Map> sorted =
map.entrySet()
.stream()
.sorted(comparing(e -> ex.get(e.getKey()), reverseOrder()))
.collect(toMap(
Map.Entry::getKey,
e -> e.getValue().stream().sorted(comparing(ex::get, reverseOrder())).collect(toList()),
(v1, v2) -> { throw new IllegalStateException(); },
LinkedHashMap::new
));
This creates a Stream of the entries of the map, sorts them in reverse order according the count of keys for that entry's key and finally collects that into a map where the new value is sorted in reverse order with regard to the count of each integer (ex::get
). The collecting map is a LinkedHashMap
to preserve encounter order.
Output:
{1=[2, 3, 0], 2=[4, 1, 0], 3=[4, 1, 5], 4=[2, 3, 5], 0=[1, 2], 5=[4, 3]}
Static imports used:
import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;