Search code examples
javajava-streamspeedment

How to sort a Map by value with java stream?


I wanted to sort my map by value, but I do not know how to do it. I have this code to put the values in the map:


Map<Tuple7<Integer, String, Double, String, String, String, String>, Double> grouped = joinFirst.stream().limit(60)
                .collect(groupingBy(t->Tuples.of(
                        t.get0().getCCustkey(),
                        t.get0().getCName(),
                        t.get0().getCAcctbal().doubleValue(),
                        t.get0().getCPhone(),
                        t.get3().getNName(),
                        t.get0().getCAddress(),
                        t.get0().getCComment()),
                        Collectors.summingDouble((t -> t.get2().getLExtendedprice().doubleValue()*(1-t.get2().getLDiscount().doubleValue()))
                        )));

I wanted to sort by the value that is computed in summingDouble.


Solution

  • Can you try with this.

     Map<Tuple7<Integer, String, Double, String, String, String, String>, 
    Double> result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<Tuple7<Integer, String, Double, String, 
    String, String, String>, Double>comparingByValue().reversed())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));