Java 中 Stream 的常见用法

流的处理,主要有三种关键性操作:

  1. 流的创建
  2. 中间操作( intermediate operation)
  3. 最终操作(terminal operation)

1. 创建Stream

  1. 通过已有集合创建stream流(List.stream()
  2. 通过Stream类创建stream流(Stream.of()

2. Stream中间操作

  1. filter:通过设置的条件过滤出元素
  2. map:映射每个元素到对应的结果
  3. limit/skip:limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素
  4. sorted:用于对流进行排序
  5. distinct:用来去重
List<String> list = Arrays.asList("Hollis", "HollisChuang", "hollis", "H ello", "HelloWorld", "Hollis");
Stream s = list.stream()
        .filter(string -> string.length() <= 6)// 过滤出长度<=6的string ["Hollis", "hollis", "Hello", "Hollis"]
        .map(String::length)// 将string内容映射成string的长度// [6, 6, 5, 6]
        .sorted()// 排序[5,6,6,6]
        .limit(3)// 前三个[5,6,6]
        .distinct();// 去重[5,6]

3. 最终操作

  1. forEach:迭代stream中的每个数据
  2. count:统计stream中的元素个数
  3. collect:一个归约操作,可以接受各种做法作为参数,将stream中的元素累积成一个汇 总结果——collect(Collectors.toList());
List<String> list = Arrays.asList("Hollis", "HollisChuang", "hollis", "H ello", "HelloWorld", "Hollis");
List<Integer> collect = list.stream()
        .filter(s -> s.length() <= 6)
        .map(String::length)
        .limit(3)
        .distinct()
        .collect(Collectors.toList());

针对某些属性内容进行去重(一个 Case)

ArrayList<RuleEngine> collect = list.stream().collect(
        Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(re -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("triggerMetadata", re.getTriggerMetadata());
                    map.put("actionIds", re.getActionIds());
                    map.put("reActionIds", re.getReActionIds());
                    map.put("invokerStyle", re.getInvokerStyle());
                    map.put("invokeType", re.getInvokeType());
                    map.put("cron", re.getCron());
                    map.put("sql", re.getSql());
                    return JSONUtil.toJsonStr(map);
                }))), ArrayList::new)
);
return collect.isEmpty() ? null : collect;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值