Search code examples
javadictionaryjava-stream

Reverse sorting a Map by value in Java using stream


I have a TreeMap that looks like that:

{AMZ=12.733334, APL=10.133334, FBK=21.4, GGL=30.599998, GHB=4.6, MCS=11.433334}

I want to only retains the entries containing the 3 highest values. I tried to do it that way:

TreeMap<String, Float> ThreeBestStocksMean = new TreeMap<>();
ThreeBestStocksMean = stocksMean.entrySet()
       .stream()
       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
       .limit(3)
       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (key1, key2) -> key1, TreeMap::new));
System.out.println(ThreeBestStocksMean.toString());

I get this:

{APL=10.133334, GHB=4.6, MCS=11.433334}

As you can see it is the exact opposite of what I want. It gave me the 3 lowest value although I want the 3 highest.

Do I use Comparator.reverseOrder() wrongly? In fact it produces the exact same result as if it wasn't there. I also tried with Map.Entry.<String, Float>comparingByValue().reversed() for the same result.

Edit:

The code above works, I had some leftovers in my code above that made it not work.


Solution

  • Can you try building/compiling the code, I tried replicating the code as below and I am getting the expected output - {AMZ=12.733334, FBK=21.4, GGL=30.599998}

    import java.util.*;
    import java.util.stream.Collectors;
    
    public class MyClass {
    public static void main(String args[]) {
      TreeMap<String, Double> ThreeBestStocksMean = new TreeMap<>();
      TreeMap<String, Double> stocksMean = new TreeMap<>();
      stocksMean.put("AMZ",12.733334);
      stocksMean.put("APL",10.133334);
      stocksMean.put("FBK",21.4);
      stocksMean.put("GGL",30.599998);
      stocksMean.put("GHB",4.6);
      stocksMean.put("MCS",11.433334);
    
      ThreeBestStocksMean = stocksMean.entrySet()
       .stream()
       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
       .limit(3)
       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (key1, key2) -> key1, TreeMap::new));
       System.out.println(ThreeBestStocksMean.toString());
     }
    }