为什么要用Stream API
无存储。stream不是一种数据结构,它只是某种数据源的一个视图,数据源可以是一个数组,Java容器或I/O channel等。
为函数式编程而生。对stream的任何修改都不会修改背后的数据源,比如对stream执行过滤操作并不会删除被过滤的元素,而是会产生一个不包含被过滤元素的新stream。
创建Stream 流的方式
Collection 提供了两个方法一种是stream() 串行流,还一种parallelStream() 并行流,
1.集合创建stream
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
2.数组创建stream
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);
3.通过 Stream 类中静态方法 of()
Stream<Integer> stream = Stream.of(1,2,3,4,5,6);
4.创建无限流
//迭代
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 1);
Stream的中间操作
1.filter(过滤):接收 Lambda , 从流中排除某些元素
例:
List<Employee> employeeList = Arrays.asList(
new Employee(1, "小赵", 18),
new Employee(1, "小钱", 19),
new Employee(1, "小孙", 20),
new Employee(1, "小李", 21),
new Employee(1, "小周", 22),
new Employee(1, "小吴", 23),
new Employee(1, "小郑", 24),
new Employee(1, "小王", 25)
);
/**
* 过滤出年龄大于20的员工
*/
@Test
public void stream(){
employeeList.stream().filter(e -> e.getAge() > 20).forEach( System.out::println);
}
输出:
2.distinct (去重)
List<Employee> employeeList = Arrays.asList(
new Employee(1, "小赵", 18),
new Employee(1, "小赵", 18),
new Employee(1, "小赵", 18),
new Employee(1, "小钱", 19),
new Employee(1, "小孙", 20),
new Employee(1, "小李", 21),
new Employee(1, "小周", 22),
new Employee(1, "小吴", 23),
new Employee(1, "小郑", 24),
new Employee(1, "小王", 25)
);
/**
* 去重
*/
@Test
public void stream2(){
Stream<Employee> distinct = employeeList.stream().distinct();
distinct.forEach(System.out::println);
}
输出:
如果不去重直接遍历则为
3.limit (截取前面maxSize条数据)
可以根据过滤条件组合,如
4.map(用于映射每个元素到对应的结果)
针对流中每一个元素进行转化操作
/**
* 将集合中每一个字符串转为大写
*/
@Test
public void mapTest() {
List<String> list = Arrays.asList("aaa", "bbb", "ccc");
// 使用Stream管道流
list.stream().map(s -> s.toUpperCase()).collect(Collectors.toList()).forEach(System.out::println);
}
输出结果为: