sortBy在Lightweight-Stream-API中按降序排列

时间:2018-04-24 17:00:47

标签: java android java-stream lightweight-stream-api

我尝试使用Lightweight-Stream-API来支持低于API-24的支持。它按升序排序,但如何降序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 个答案:

答案 0 :(得分:2)

之前没有听说过或使用过此库,但是一些研究似乎建议您只需将sortBy方法更改为:

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

{{1}}

这与此处的最后一种测试方法类似:

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