0

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.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
joaoprog
  • 45
  • 7
  • `.sorted(Comparator.comparing(Map.Entry::getValue))` – Naman Jun 12 '19 at 09:41
  • @Naman It does not work. I have this error: ```Error:(98, 152) java: incompatible types: cannot infer type-variable(s) T,U (argument mismatch; invalid method reference method getValue in interface java.util.Map.Entry cannot be applied to given types required: no arguments found: java.lang.Object reason: actual and formal argument lists differ in length) ``` – joaoprog Jun 12 '19 at 09:43

1 Answers1

2

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()));
Mak
  • 1,068
  • 8
  • 19
  • How did you know that the OP wants `reversed()`? You can use `.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))`, which does not require repeating the entire tuple type, by the way. – Holger Jun 12 '19 at 15:48