stream流常用方法
时间: 2023-10-29 10:06:32 浏览: 40
在Java中,流(Stream)是一种用于处理集合对象的机制。它提供了一种函数式的编程方式,可以通过流操作来对集合进行过滤、映射、排序等操作,大大简化了集合处理的代码。
下面是一些常用的流方法:
1. filter():过滤集合中的元素,返回一个新的流。
2. map():对集合中的元素进行映射操作,返回一个新的流。
3. sorted():对集合中的元素进行排序,返回一个新的流。
4. distinct():去除集合中的重复元素,返回一个新的流。
5. limit():截取集合中的前n个元素,返回一个新的流。
6. skip():跳过集合中的前n个元素,返回一个新的流。
7. forEach():对集合中的每个元素执行指定的操作。
8. reduce():对集合中的元素进行归约操作,返回一个计算结果。
9. collect():将流中的元素收集到指定的容器中。
10. flatMap():将一个流中的每个元素转换为一个流,并将所有流中的元素合并成一个流。
这些方法可以通过链式调用来组合使用,例如:
```
List<String> list = Arrays.asList("apple", "banana", "orange");
List<String> result = list.stream()
.filter(s -> s.startsWith("a"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
```
这段代码中,首先创建了一个包含三个字符串的列表,然后将它转换为一个流。接着使用 filter() 方法过滤以字母'a'开头的字符串,然后使用 map() 方法将字符串转换为大写形式。之后使用 sorted() 方法对流中的元素进行排序,最后使用 collect() 方法将结果收集到一个新的列表中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)