Java8 Stream详解~排序:sorted
生活随笔
收集整理的這篇文章主要介紹了
Java8 Stream详解~排序:sorted
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
sorted,中間操作。有兩種排序:
-
sorted():自然排序,流中元素需實現Comparable接口
-
sorted(Comparator com):Comparator排序器自定義排序
「案例:將員工按工資由高到低(工資一樣則按年齡由大到小)排序」
public class StreamTest {public static void main(String[] args) {List<Person> personList = new ArrayList<Person>();personList.add(new Person("Sherry", 9000, 24, "female", "New York"));personList.add(new Person("Tom", 8900, 22, "male", "Washington"));personList.add(new Person("Jack", 9000, 25, "male", "Washington"));personList.add(new Person("Lily", 8800, 26, "male", "New York"));personList.add(new Person("Alisa", 9000, 26, "female", "New York"));// 按工資升序排序(自然排序)List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());// 按工資倒序排序List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());// 先按工資再按年齡升序排序List<String> newList3 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());// 先按工資再按年齡自定義排序(降序)List<String> newList4 = personList.stream().sorted((p1, p2) -> {if (p1.getSalary() == p2.getSalary()) {return p2.getAge() - p1.getAge();} else {return p2.getSalary() - p1.getSalary();}}).map(Person::getName).collect(Collectors.toList());System.out.println("按工資升序排序:" + newList);System.out.println("按工資降序排序:" + newList2);System.out.println("先按工資再按年齡升序排序:" + newList3);System.out.println("先按工資再按年齡自定義降序排序:" + newList4);} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Java8 Stream详解~排序:sorted的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 命令行 解析模块 optp
- 下一篇: 安卓逆向_25 --- 密码学 之 《