Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
montyynis Avatar asked Mar 05 '23 03:03

montyynis


1 Answers

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.

like image 108
Ousmane D. Avatar answered Mar 16 '23 01:03

Ousmane D.