Stream流使用总结

一.创建流
通常通过数组或者集合方式创建

Arrays.stream(arr)
list.stream()

二.中间操作
map 映射
filter 过滤
distinct 去重
flatMap 扁平化(流中得到集合合并后,形成新的流)
sort 排序
peek 中间操作的forEach
skip/limit 舍弃/截取(不常用)

// 按重量升序排列
	List<Apple> list1 = appleStore.stream().sorted(Comparator.comparing(Apple::getWeight, Comparator.
                nullsLast(Comparator.naturalOrder()))).peek(System.out::print).collect(Collectors.toList());

// flatMap 遍历得到一个集合,合并后得到新的流,进行操作
	List<List<Apple>> all = new ArrayList<>();
        all.add(appleStore);
        all.add(appleStore2);
    List<Integer> ids = all.stream().flatMap(Collection::stream).map(Apple::getId).collect(Collectors.toList());

三.终止操作
匹配和查找
anyMatch 只要有一个匹配,返回true
allMatch 全部匹配,返回true
noneMatch 都不匹配,返回true
findFirst 返回第一个元素
findAny 返回任意元素

归约 reduce

		//求list中的和,以0为基数
        Integer reduce = integers.stream().reduce(0, (a, b) -> a + b);
        //Integer的静态方法
        int sum = integers.stream().reduce(0, Integer::sum);
————————————————
版权声明:本文为CSDN博主「爱思考的王同学」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_37967166/article/details/89153568

收集器
转list
转set
转map
字符串拼接

	// list
    List<String> list = appleStore.stream().map(Apple::getColor).collect(Collectors.toList());
        System.out.println(list);
    // set
    Set<String> set = appleStore.stream().map(Apple::getColor).collect(Collectors.toSet());
        System.out.println(set);
    // map 遇到key相同,后者取代前者
    Map<String, Apple> map = appleStore.stream()
                .collect(Collectors.toMap(Apple::getColor, item -> item, (k1, k2) -> k2));
	// 拼接成一个字符串
	list.stream().collect(Collectors.joining("_"));

分组
groupingBy

// 苹果按颜色分类,并求平均重量
        appleStore.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors
                .averagingInt(value -> value.getWeight()))).forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值