ArrayList的stream方法
时间: 2023-08-21 11:04:28 浏览: 35
`stream()`方法是Java 8中ArrayList类的一个成员方法,它返回一个顺序流(Stream)对象,该流对象包含了ArrayList中的所有元素。可以使用该流对象对ArrayList进行各种操作,如过滤、排序、映射等。下面是一个简单的例子:
```java
import java.util.ArrayList;
import java.util.stream.Collectors;
public class ArrayListStreamExample {
public static void main(String[] args) {
ArrayList<Integer> numbersList = new ArrayList<>();
numbersList.add(1);
numbersList.add(2);
numbersList.add(3);
numbersList.add(4);
numbersList.add(5);
// 使用stream过滤出大于3的元素
ArrayList<Integer> filteredList =
(ArrayList<Integer>) numbersList.stream().filter(n -> n > 3).collect(Collectors.toList());
System.out.println(filteredList); // 输出 [4, 5]
}
}
```
在上面的例子中,使用`stream()`方法获取了一个流对象,然后使用`filter()`方法过滤出大于3的元素,最后使用`collect()`方法将结果收集到一个新的ArrayList中。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)