sortBy in descending order in Lightweight-Stream-API

499 views Asked by At

I'm trying to use Lightweight-Stream-API for supporting less than API-24. It works with ascending order but how to do it descending sortBy().

 List<Person> persons = Arrays.asList(
                new Person("Bill", 30),
                new Person("Ali", 25),
                new Person("Apula", 40),
                new Person("Calin", 18),
                new Person("Adomin", 20),
                new Person("Amkita", 35),
                new Person("Della", 40)
        );

List<Person> result = com.annimon.stream.Stream.of(persons)
                        .filter(x -> x.getName().startsWith("A"))
                        .sortBy(Person::getAge) // how to make it descending?
                        .limit(2)
                        .toList();
1

There are 1 answers

0
Ousmane D. On BEST ANSWER

Not heard of or used this library before but a bit of research seems to suggest you can simply change your sortBy method to:

.sortBy(p -> -p.getAge())...

or

.sortBy(new Function<Person, Integer>(){
      @Override
       public Integer apply(Person p){ 
           return -p.getAge();
      }
})...

This is similar to the last test method here:

https://github.com/aNNiMON/Lightweight-Stream-API/blob/master/stream/src/test/java/com/annimon/stream/streamtests/SortByTest.java