使用流过滤的优势
在 Stream 流出现以前,如果我们想对一个集合进行迭代,可能会使用 forEach 或者 for in 循环,如果在迭代过程中还需要进行一些判断,可能会需要多个循环.
相同的功能,用 Stream 流加 lambda 表达式实现代码量大大减少(实际上循环次数也会有一定幅度减少),而且所做的操作越多,用 Stream 流的优势就越明显。因此 Stream 流的出现主要是为了简化迭代的操作,提高迭代效率。
List<Integer> list = new ArrayList<>(Arrays.asList(3,5,2,9,1,6,8,7));
list.stream().filter(integer -> integer>5).sorted().forEach(System.out::println);
转载于https://zhuanlan.zhihu.com/p/340665466
例子
1.输出符合表达式的每一个对象
employees.stream().filter(p -> p.getAge() > 21).forEach(System.out::println);
//输出每一个对象
2.返回一个符合表达式的集合
employees.stream().filter(predicate).collect(Collectors.<Employee>toList());
//返回一个集合
3.返回符合表达式的集合的第一个对象
employees.stream().filter(p -> p.getAge() > 21).findFirst();
4.抽取对象中所有的id的集合
employees.stream().map(Employee::getId).collect(Collectors.toList());
转载于https://blog.csdn.net/xinyang12138/article/details/86526540