montyynis
montyynis

Reputation: 143

Ordering HashMap by the size of the value set

I would like to order a HashMap:

Map<Integer, Set<Integer>> unsorted

by the size of the value set. I attempted to do it as follows:

        Map<Integer, Set<Integer>> sorted = unsorted.entrySet().stream()
            .sorted(comparingInt(e->e.getValue().size()))
            .collect(toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    LinkedHashMap::new
            ));

but got an error

"Non-static method cannot be referenced from a static context"

. I am new to Java 8 Streams and am clearly missing something trivial - what is it?

Upvotes: 4

Views: 119

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

Short answer: You're missing the merge function:

.collect(toMap(Map.Entry::getKey,Map.Entry::getValue, (l, r) -> l, LinkedHashMap::new));

i.e. (l, r) -> l above.

Long Answer:

You're wanting to use the toMap overload which takes a "mapFactory" as the doc calls it, essentially it's a supplier providing a new empty map into which the results will be inserted.

Now look at how the overload is defined:

toMap​(Function<? super T,? extends K> keyMapper,
      Function<? super T,? extends U> valueMapper,
      BinaryOperator<U> mergeFunction,
      Supplier<M> mapFactory)

as you can see a mergeFunction is required in order to provide a "mapFactory" otherwise the compiler will think you're attempting to use this overload:

toMap​(Function<? super T,? extends K> keyMapper,
      Function<? super T,? extends U> valueMapper,
      BinaryOperator<U> mergeFunction)

hence it fails with the aforementioned error.

Upvotes: 7

Related Questions