Ad Infinitum Ad Infinitum - 1 month ago 8
Java Question

Get a sorted list from a Map via Stream API

I am trying to achieve the following scenario with the

Stream API
but with no success.

I have the following graph. The key is the name of the person and the set has the name of friends of the person (key).

Map<String, Set<String>> fooGraph


I want to have a sorted ArrayList based on the number of friends (popularity), a person has.

For example,

this is the
fooGraph
with its values

x -> a,b,c

y -> a

z -> a,b,c,d,e,f

t -> a,b,c,d


and at the end of the day, I want to have a list based on the popularity of a person. The list should look like the following

z, t, x, y


How can it be achieved with
Stream API
?

Answer
List<String> sorted = fooGraph.entrySet()
        .stream()
        .sorted(Comparator.comparing(e -> e.getValue().size(), Comparator.reverseOrder()))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
Comments