栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Mutable reduction(动态规约)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Mutable reduction(动态规约)

官方文档解释

简介

动态规约操作会把Stream(流)中元素添加到动态容器中,例如Collectin或StringBuilder。
如果我们想把Stream中的一堆字符串拼接成一个长字符串的话,一个用以下操作:

     String concatenated = strings.reduce("", String::concat)

这种方式虽然管用,但是性能不够优秀,时间复杂度是O(N2)。
为了更高效得完成这类任务,Java提出了动态规约。

实现方式collect()函数

collect()函数会以动态规约的方式处理数据,并以集合的形式返回处理后的结果。

三个参数

collect()函数需要三个参数:

  • supplier:生成用来保存结果的容器
  • accumulator:处理输入数据,数据会经过它的处理后保存到容器中
  • combiner:把产生的结果拼接到另一个容器中(用于多线程并行)

A collect operation requires three functions: a supplier function to construct new instances of the result container, an accumulator function to incorporate an input element into a result container, and a combining function to merge the contents of one result container into another. The form of this is very similar to the general form of ordinary reduction:

  R collect(Supplier supplier,
               BiConsumer accumulator,
               BiConsumer combiner);
Collector

可以用Collector,把这三个参数结合到一起。

 R collect(Collector collector)
一个拼接字符串的例子:
	ArrayList strings = new ArrayList<>();
	for (T element : stream) {
         strings.add(element.toString());
	}
	
	 //三个参数方式改写
     ArrayList strings = stream.collect(() -> new ArrayList<>(),
                                           		(c, e) -> c.add(e.toString()),
                                                (c1, c2) -> c1.addAll(c2));
     //三个参数方式改写                                           
     List strings = stream.map(Object::toString)
                                  .collect(ArrayList::new, 
                                  		   ArrayList::add, 
                                  		   ArrayList::addAll);
     //Collector改写                             		   
     List strings = stream.map(Object::toString)
                                  .collect(Collectors.toList());
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/821260.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号