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> R collect(Supplier<R> supplier,
               BiConsumer<R, ? super T> accumulator,
               BiConsumer<R, R> combiner);

Collector

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

<R,A> R collect(Collector<? super T,A,R> collector)

一个拼接字符串的例子:

	ArrayList<String> strings = new ArrayList<>();
	for (T element : stream) {
         strings.add(element.toString());
	}
	
	 //三个参数方式改写
     ArrayList<String> strings = stream.collect(() -> new ArrayList<>(),
                                           		(c, e) -> c.add(e.toString()),
                                                (c1, c2) -> c1.addAll(c2));
     //三个参数方式改写                                           
     List<String> strings = stream.map(Object::toString)
                                  .collect(ArrayList::new, 
                                  		   ArrayList::add, 
                                  		   ArrayList::addAll);
     //Collector改写                             		   
     List<String> strings = stream.map(Object::toString)
                                  .collect(Collectors.toList());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值