| ⼀个终端操作, ⽤于对流中的数据进⾏归集操作,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() |
| 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"); |
| |
| List<String> results = list.stream().collect(Collectors.toList()); |
| |
| list.stream().collect(Collectors.toSet()); |
| |
| List<String> result = list.stream().collect(Collectors.toCollection(LinkedList::new)); |
| |
| 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() |
| 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); |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
2021-08-25 vue常见错误