0

I'm new in Java and now I try lambda/stream.

How can I sort the Map by value?

I tried as follows, but it's not correct:

time = time.entrySet().stream()
           .sorted(Comparator.comparing(Map.Entry::getValue))
           .collect(Collectors.toMap((String)Map.Entry::getKey, 
                      (Long)Map.Entry::getValue, LinkedHashMap::new));

I found the following method, but don't know how to use it:

Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,   
                        Function<? super T, ? extends U> valueMapper,   
                        BinaryOperator<U> mergeFunction,   
                        Supplier<M> mapSupplier)
Eran
  • 387,369
  • 54
  • 702
  • 768
Khilarian
  • 249
  • 1
  • 9

1 Answers1

0

You forgot to specify the merge function.

time = time.entrySet()
           .stream()
           .sorted(Comparator.comparing(Map.Entry::getValue))
           .collect(Collectors.toMap(Map.Entry::getKey, 
                                    Map.Entry::getValue,
                                    (v1,v2)->v1,
                                    LinkedHashMap::new));

BTW, assuming that time is not a raw Map, you don't have to cast the key to String and the value to Long. And trying to cast the method references Map.Entry::getKey and Map.Entry::getValue is wrong anyway, since the method references implement the Function interface, so they shouldn't be cast to String or Long if you want your code to pass compilation.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Great thanks! I see it work. By can you help to understand- what (v1,v2)-> v1 means? It means that if v1 and v2 has the same value, first one in map will be v1, right? – Khilarian Dec 10 '19 at 11:53
  • @Khilarian it means that if the Stream maps two values to the same key, it will use that merge function, which will take the 2 values and return the first value. Since your Stream source is a Map, there will be no values to merge, so you can pass any merge function here and it won't affect the result. – Eran Dec 10 '19 at 11:56
  • thanks ) it's easier to understand that I read earlier)) – Khilarian Dec 10 '19 at 12:03