java stream-中间操作 distinct、limit、skip、sorted 作者:马育民 • 2023-04-07 21:58 • 阅读:10066 # distinct ``` List list = new ArrayList<>(); Collections.addAll(list,"李雷", "韩梅梅", "lucy", "lucy","李雷"); list.stream() .distinct() // 过滤重复的数据,相当于 sql中的distinct .forEach(item -> System.out.println(item)); ``` # limit 从流中获取前 `n` 个数据 ``` List list = new ArrayList<>(); Collections.addAll(list,"李雷", "韩梅梅", "lucy", "lisi","李小四"); list.stream() .limit(3) // 取出前3个数据 .forEach(item -> System.out.println(item)); ``` # skip 跳过前 `n` 个数据,取出后面所有的元素 ``` List list = new ArrayList<>(); Collections.addAll(list,"李雷", "韩梅梅", "lucy", "lili","李小四"); list.stream() .skip(3) // 跳过前3个数据,取出后面所有的元素 .forEach(item -> System.out.println(item)); ``` # skip和limit 联合使用 集合中有 `"李雷", "lucy", "lili","李小四"` ,打印出 `lucy、lili` ### 方式一 ``` List list = new ArrayList<>(); Collections.addAll(list,"李雷", "lucy", "lili","李小四"); list.stream() .skip(1) // 跳过前1个数据,取出后面所有的元素,即:"lucy", "lili","李小四" .limit(2) // 取出前2个数据,即:"lucy", "lili" .forEach(item -> System.out.println(item)); ``` ### 方式二 ``` List list = new ArrayList<>(); Collections.addAll(list,"李雷", "lucy", "lili","李小四"); list.stream() .limit(3) // 取出前3个数据,即:"李雷", "lucy", "lili" .skip(1) // 跳过前1个数据,取出后面所有的元素,即:"lucy", "lili" .forEach(item -> System.out.println(item)); ``` # sorted 按照指定规则排序 ### 例子 - 默认从小到大 ``` List list = new ArrayList<>(); Collections.addAll(list,10,15,2,4,8); list.stream() .sorted() .forEach(item -> System.out.println(item)); } ``` ### 例子 - 从大到小 ``` List list = new ArrayList<>(); Collections.addAll(list,10,15,2,4,8); list.stream() .sorted( (item2,item1) -> item1 - item2) // 倒序 .forEach(item -> System.out.println(item)); ``` 原文出处:http://malaoshi.top/show_1IX5HCIM9kXd.html