展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

collector收集器和joining函数

  • collect()⽅法的作⽤
⼀个终端操作, ⽤于对流中的数据进⾏归集操作,collect⽅法接受的参数是⼀个Collector
有两个重载⽅法,在Stream接⼝⾥⾯
//重载⽅法⼀
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T>
accumulator, BiConsumer<R, R>combiner);
//重载⽅法⼆
<R, A> R collect(Collector<? super T, A, R> collector);
  • 常见收集器
Collectors.toList()
Collectors.toMap()
Collectors.toSet()
  • Collectors.toList()详情
public static <T>
Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
ArrayList::new,创建⼀个ArrayList作为累加器
List::add,对流中元素的操作就是直接添加到累加器中
reduce操作, 对⼦任务归集结果addAll,后⼀个⼦任务的结果直接全部添加到前⼀个⼦任务结果中
CH_ID 是⼀个unmodifiableSet集合
  • Collectors.toCollection() :⽤⾃定义的实现Collection的数据结构收集
Collectors.toCollection(LinkedList::new)
Collectors.toCollection(CopyOnWriteArrayList::new)
Collectors.toCollection(TreeSet::new)
  • 案例
public class Main {
public static void main(String[] args) throws Exception {
// 新建集合
List<String> list = Arrays.asList("sdfsdf","xxxx","bbb","bbb");
// 转为ArrayList
List<String> results = list.stream().collect(Collectors.toList());
// 转为set
list.stream().collect(Collectors.toSet());
// 转为LinkedList
List<String> result = list.stream().collect(Collectors.toCollection(LinkedList::new));
// 转为CopyOnWriteArrayList
List<String> result1 = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
Set<String> stringSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
System.out.println(result);
System.out.println(stringSet);
}
}
  • 拼接函数 Collectors.joining
//3种重载⽅法
Collectors.joining()
Collectors.joining("param")
Collectors.joining("param1", "param2", "param3")
  • 案例
public class Main {
public static void main(String[] args) throws Exception {
// 直接拼接
List<String> list = Arrays.asList("springboot教程","springcloud教程","java教程","架构教程");
String result1 = list.stream().collect(Collectors.joining());
System.out.println(result1);
// 使用自定义的分隔符
String result2 = list.stream().collect(Collectors.joining("||"));
System.out.println(result2);
// 使用前后缀
String result3 = list.stream().collect(Collectors.joining("||","[","]"));
System.out.println(result3);
// 使用前后缀
String result = Stream.of("springboot","mysql","html5","css3").collect(Collectors.joining(",","[","]"));
System.out.println(result);
}
}
posted @   DogLeftover  阅读(369)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
历史上的今天:
2021-08-25 vue常见错误
点击右上角即可分享
微信分享提示