Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 lambda: sort a stream in reverse order?

I have this list that I want to order in reserve order, but I didn't find any .reversed() function in autocomplete assist

 myMenus(user)
                .stream()
                .filter(mps ->  mps.get1PercentageChange() > 0 &&
                                mps.get2PercentageChange() > 0 &&
                                mps.get3PercentageChange() > 0 &
                                mps.get4PercentageChange() > 0)
                .sorted(comparing(mps -> mps.getDailyPercentageChange()))
                .collect(toList());

I have also tried:

myMenus(user)
        .stream()
        .filter(mps ->  mps.get1PercentageChange() > 0 &&
                        mps.get2PercentageChange() > 0 &&
                        mps.get3PercentageChange() > 0 &
                        mps.get4PercentageChange() > 0)
        .sorted(comparing(mps -> mps.getDailyPercentageChange()).reversed())
        .collect(toList());

but then I have the compilation error:

Cannot infer type argument(s) for <T, U> comparing(Function<? super T,? 
     extends U>)
like image 589
en Peris Avatar asked Jun 01 '18 14:06

en Peris


People also ask

How do you sort a stream in reverse order?

Java stream provides a method sorted() which can sort List in ascending and descending order without you to write any complex logic. By default sorting() method sorts the list in ascending order. If we want to sort in descending order we need to pass Comparator. reverseOrder() in sorted() method as a parameter.

How do I sort a list in reverse order in Java 8?

To get the list in the reverse order, we need to use Collections. reverseOrder() and Collections. sort() methods together.

How I sort the collection using stream?

Stream sorted() in Java Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.


1 Answers

It's a type inference issue. You'll need to help the compiler out.

few things you could try:

.sorted(comparing(T::getDailyPercentageChange).reversed())

or

.sorted(comparing((T mps) -> mps.getDailyPercentageChange()).reversed())

Where T is the type of elements being compared.

like image 193
Ousmane D. Avatar answered Nov 15 '22 09:11

Ousmane D.