Java stream sort reversed after sum

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

get a compile error, cannot resolve method r.getA(), but

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

is ok,

so how can I do a sort by r -> r.getA() + r.getB() and get it reversed?

Naman :

One way to do that would be to type cast the ToDoubleFunction as:

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

Though I would have preferred explicitly creating a Comparator<C> as

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

Note: C here is your object type, which constitutes the list in question as well.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102126&siteId=1