流的处理,主要有三种关键性操作:
- 流的创建
- 中间操作( intermediate operation)
- 最终操作(terminal operation)
1. 创建Stream
- 通过已有集合创建stream流(
List.stream()
) - 通过Stream类创建stream流(
Stream.of()
)
2. Stream中间操作
- filter:通过设置的条件过滤出元素
- map:映射每个元素到对应的结果
- limit/skip:limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素
- sorted:用于对流进行排序
- 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. 最终操作
- forEach:迭代stream中的每个数据
- count:统计stream中的元素个数
- 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;