Ad Infinitum Ad Infinitum - 6 months ago 32
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
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

List<String> sorted = fooGraph.entrySet()
        .sorted(Comparator.comparing(e -> e.getValue().size(), Comparator.reverseOrder()))