ArrayList的stream方法
时间: 2023-08-22 10:05:19 浏览: 61
ArrayList是Java集合框架中的一种集合类,它可以用来存储一组对象。在Java 8中,ArrayList新增了stream()方法,用于将集合转换为流,进而进行各种数据处理操作,例如过滤、映射、排序等。
下面是一个简单的例子,演示如何使用ArrayList的stream方法过滤出所有偶数:
```
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayListStreamExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // 输出 [2, 4]
}
}
```
在上面的例子中,我们首先创建了一个包含数字1到5的ArrayList。然后,我们使用stream()方法将其转换为流,并使用filter()方法对流进行过滤,只保留偶数。最后,我们使用collect()方法将过滤后的结果收集到一个新的List中,并输出该List。
通过使用ArrayList的stream方法,我们可以更加方便地对集合进行各种数据处理操作,提高代码的可读性和可维护性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)