java 8 中 stream 流操作

流操作分为 中间操作终止操作

中间操作就是流中的数据进行一系列操作,所以一个流可以进行多个中间操作

终止操作用于返回我们最终需要的数据,只能有一个终止操作放在最后

优点:用起来非常的方便,而且提高代码的整洁度!

中间操作常用的方法:

List<Integer> list = Arrays.asList(10, 20, 30, 40, 40, 20);

// 1.对list中数据进行筛选操作
List<Integer> listFilter = list.stream().filter(x -> x > 25).collect(Collectors.toList());

// 2.对list中的每个数据操作一下,然后转化为list
List listMap = list.stream().map(x -> x + x * 5).collect(Collectors.toList());

// 3.保留前3个元素
List<Integer> listLimit = list.stream().limit(3).collect(Collectors.toList());

// 4.跳过3个元素
List<Integer> listSkip = list.stream().skip(3).collect(Collectors.toList());

// 5.剔除重复元素
List<Integer> listDistinct = list.stream().distinct().collect(Collectors.toList());

// 6.sorted:对list中的元素进行流排序
// 7.peek:流不变,会把每个元素传入进行操作,可以进行调试等操作
List<Integer> listSorted =
        list.stream()
                .sorted() //对list中的元素进行流排序
                .peek(x -> {
                    if(x > 25){
                        System.out.println(x); //把每个大于25的数字打印出来
                    }}).collect(Collectors.toList());

终止操作常用的方法:

List<Integer> list = Arrays.asList(10, 20, 30, 40, 40, 20);
// 计算出最大值
Optional<Integer> listMax = list.stream().max(Integer::compareTo);

// 计算最小值
Optional<Integer> listMin = list.stream().min(Integer::compareTo);

// 返回第一个值
Optional<Integer> listFirst = list.stream().findFirst();

// 放回任意值
Optional<Integer> listAny = list.stream().findAny();

// 任何一个满足返回true
boolean listAnyMatch = list.stream().anyMatch(x -> x > 25);

// 所有满足返回true
boolean listAllMatch = list.stream().allMatch(x -> x > 25);

// 没有满足返回true
boolean listNoneMatch = list.stream().noneMatch(x -> x > 25);

// 累加器(x为0,然后y为list中的元素,他俩相加,然后付给x,最后返回下)
Integer sum = list.stream().reduce(0,(x,y) -> x + y);
Integer sumOther = list.stream().reduce(0, Integer::sum);

深入了解博客推荐:传送门

简单了解和实践,欢迎交流学习!

发布了214 篇原创文章 · 获赞 281 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/lk1822791193/article/details/102816428