Java新特性玩转JDK8之collector收集器
流的collect()方法
- 一个终端操作, 用于对流中的数据进行归集操作,collect方法接受的参数是一个Collector
- 两个重载方法
- 方法一 ,通常用来自定义返回值类型,但在实际开发中很少使用
- 方法二,传入Collector收集器来对流中结果进行收集,实际开发中常用此方法
参数Collector 收集器
- **通常我们不会来自定义Collector收集器。**对于常用的Collector收集器,jdk 8 已经帮我们封装在 Collectors 类中。
👇
👇
Collectors 常用收集器
- 三大常用收集器
- Collectors.toList(); // 该收集器将流转换为List集合
- Collectors.toMap(); // 该收集器将流转换为map集合
- Collectors.toSet(); // 该收集器将流转换为Set集合
- 自定义Collection 的结构 数据收集
- Collectors.toCollection(LinkedList::new)
- Collectors.toCollection(CopyOnWriteArrayList::new)
- Collectors.toCollection(TreeSet::new)
- joining 收集器 👉 章节 7-2
- partitioningBy 收集器 👉 章节 7-3
- group by 收集器 👉 章节 7-4 & 7-5
- summarizing 收集器 👉 章节 7-6
课程代码
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("sdfsdf","xxxx","bbb","bbb");
// List<String> results = list.stream().collect(Collectors.toList());
// 打印 [bbb, xxxx, sdfsdf] set会去重复所以剩下三个
System.out.println(list.stream().collect(Collectors.toSet()));
// List<String> result = list.stream().collect(Collectors.toCollection(LinkedList::new));
List<String> result = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
Set<String> stringSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
// 打印 [sdfsdf, xxxx, bbb, bbb]
System.out.println(result);
// 打印 [bbb, sdfsdf, xxxx]
System.out.println(stringSet);
}
}
原文地址:https://www.yuque.com/haomingzi-kowv5/pmcs3t/ml7tlr