Java stream ordering inversion after summation

Java stream ordering inversion after summation … here is a solution to the problem.

Java stream ordering inversion after summation

list
.parallelStream()
.sorted(Comparator.comparingDouble(r -> r.getA() + r.getB()).reversed())

There was a compilation error and the method r.getA() could not be resolved, but

list
.parallelStream()                                    
.sorted(Comparator.comparingDouble(r -> r.getA() + r.getB())

No problem

So how can I sort and reverse it by r -> r.getA() + r.getB()?

Solution

One way to do this is to type ToDoubleFunction. As:

list.parallelStream()
    .sorted(Comparator.comparingDouble((ToDoubleFunction<C>) r -> r.getA() + r.getB())
            .reversed());

Although I would prefer to explicitly create a Comparator<C > as

list.parallelStream()
        .sorted(((Comparator<C>) (o1, o2) -> Double.compare(o1.getA() + o1.getB(), o2.getA() + o2.getB()))
                .reversed());

Note: C This is your object type, and it makes up the list also problematic.

Related Problems and Solutions