一:reduce

  • rudece方法:从一个流中生成一个值
  • 三个重载方法:
Optional<T> reduce(BinaryOperator<T> accumulator);

T reduce(T identity, BinaryOperator<T> accumulator);

 <U> U reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner);

二:重载方法原理

  • 一个参数

接口继承详情:

Optional<T> reduce(BinaryOperator<T> accumulator);

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
//两个静态方法,先进行忽略
} @FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
//一个默认方法,先进行忽略
}

这里可以看出,reduce方法参数为一个函数,返回值为Optional对象,BinaryOperator的作用为规定BiFunction的三个参数泛型类型要一致,也就是说只要我们对apply方法进行实现并传进去就ok了。

文档中写到:

Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value。

大致意思:使用累积函数对此流的元素执行操作,并返回一个描述结果的Optional对象。

reduce方法的效果:

   This is equivalent to:
boolean foundAny = false;
T result = null;
for (T element : this stream) {
if (!foundAny) {
foundAny = true;
result = element;
}
else
result = accumulator.apply(result, element);
}
return foundAny ? Optional.of(result) : Optional.empty();

如上文描述:用T类型对象对流进行遍历,第一个数值进行赋值,其余apply操作,并将操作的结果进行返回,等待下次继续当apply方法参数输入。

那也就是说,我们可以这样:

求和效果展示:
   		List<Integer> num = Arrays.asList(1, 2, 4, 5, 6, 7);
Integer result = num.stream().reduce((x, y) -> {
System.out.println("x:"+x);
return x + y;
}).get();
System.out.println("resutl:"+result);
//你也可以这样写,效果一样,一个为Lambda表达式,一个匿名内部类
Integer integer = num.stream().reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer a, Integer b) { return a + b;
}
}).get();
  • 两个参数

接口继承详情:

该方法的参数多了一个identity,初始值

T reduce(T identity, BinaryOperator<T> accumulator);

文档解释:

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.

大致意思:使用提供的初始值和累计函数对流进行操作,并返回一个初始值类型的计算结果。

     T result = identity;
for (T element : this stream){
result = accumulator.apply(result, element)
}
return result;

reduce方法效果:使用identity作为初始值,每遍历到一个数据,用apply方法操作并将结果返回。

计和效果展示:

        List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
Integer result = num.stream().reduce(0,(x, y) -> {
System.out.println("x:" + x);
return x + y;
});
System.out.println("resutl:" + result);
不同点:①,reduce中多了一个参数,初始值identity。②方法的返回结果为初始值identity类型的对象。
  • 三个参数

接口继承详情:

<U> U reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner); @FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u);
//一个默认方法,忽略
}

这里先看一个reduce的参数:①,U类型的初始值。②,(T,U)→U,T+U返回U类型。③组合器,(T,T)→T,T+T返回T类型。

文档描述:

这个是对于combiner组合器的描述,其他描述和前两个方法无二。

The identity value must be an identity for the combiner function.his means that for all u, combiner(identity, u) is equal to code u. Additionally, the code combiner function must be compatible with thecode accumulator function; for all u and t。

大致意思:组合器需要和累加器的返回类型需要进行兼容,combiner组合器的方法主要用在并行操作中。如果你使用了parallelStream reduce操作是并发进行的 为了避免竞争 每个reduce线程都会有独立的result combiner的作用在于合并每个线程的result得到最终结果

reduce方法运行效果:

 	   U result = identity;
for (T element : this stream){
result = accumulator.apply(result, element)
}
return result;

与前两个方法的不同点:

主要是初始值与用于遍历流的对象类型不同,可以进行许多骚操作,例如ArrayList内添加数据,StringBulider拼接数据。

非并行:向ArrayList添加数据:

向arr集合后面添加num集合的数值,由于是非并行操作,combiner组合器方法没有效果,只要参数与返回类型正确即可。

        List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
ArrayList<Integer> arr = new ArrayList<>();
arr.add(7);
arr.add(8);
arr.add(9);
arr.add(10);
List<Integer> reduce = num.stream().reduce(arr, (x, y) -> {
x.add(y);
return x;
}, (List<Integer> x, List<Integer> y) -> {
System.out.println("并行才会出现");
return x;
});
System.out.println(reduce);

并行:集合内数据求和:

	List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6);
Integer num1 = num.parallelStream().reduce(7, (x, y) -> x + y, (x, y)->{
System.out.println("这里调用一次");
return x + y;
});
System.out.println(num1);
123456

预算结果应该为1+…+7=28,然而结果为67,那这里应该是这样的,调用6个线程进行计算,每个线程都以7作为初始值进行计算,最后将每个线程进行累计操作。combiner组合器的作用应该大致为将每个线程所计算的结果进行组合。

【Java 8】 Reduce方法的更多相关文章

  1. 【Java 8】Stream通过reduce()方法合并流为一条数据示例

    在本页中,我们将提供 Java 8 Stream reduce()示例. Stream reduce()对流的元素执行缩减.它使用恒等式和累加器函数进行归约. 在并行处理中,我们可以将合并器函数作为附 ...

  2. [五]java函数式编程归约reduce概念原理 stream reduce方法详解 reduce三个参数的reduce方法如何使用

    reduce-归约 看下词典翻译: 好的命名是自解释的 reduce的方法取得就是其中归纳的含义 java8 流相关的操作中,我们把它理解 "累加器",之所以加引号是因为他并不仅仅 ...

  3. paip.java OutOfMemoryError 解决方法o33

    paip.java OutOfMemoryError 解决方法o33 java.lang.OutOfMemoryError: Requested # java.lang.OutOfMemoryErro ...

  4. JavaScript - reduce方法,reduceRight方法 (Array)

    JavaScript - reduce方法 (Array) 解释:reduce() 方法接收一个函数作为累加器(accumulator),数组 中的每个值(从左到右)开始合并,最终为一个值. 语法:a ...

  5. oracle调用JAVA类的方法

    导入jar包 在oracle中导入需要的jar包,我们把编辑好的java类打成jar包,直接在oarcle里面写简单的调用就可以了,  1.操作系统需要拥有支持loadjava命令的jdk.  2.加 ...

  6. JavaScript数组的reduce方法详解

    数组经常用到的方法有push.join.indexOf.slice等等,但是有一个经常被我们忽略的方法:reduce,这个方法简直强大的不要不要的. 我们先来看看这个方法的官方概述:reduce()  ...

  7. Java中的方法应用

    一.如何定义java中的方法 所谓方法,就是用来解决一类问题的代码的有序组合,是一个功能模块. 语法: 1. 访问修饰符:方法允许被访问的权限范围, 可以是 public.protected.priv ...

  8. JavaScript中reduce()方法

    原文  http://aotu.io/notes/2016/04/15/2016-04-14-js-reduce/   JavaScript中reduce()方法不完全指南 reduce() 方法接收 ...

  9. Java Runtime.availableProcessors()方法

    Java Runtime.availableProcessors()方法用法实例教程.   描述 java.lang.Runtime.availableProcessors() 方法返回到Java虚拟 ...

随机推荐

  1. nio实现文件夹内容的监听

    参考的博客 package com.jp.filemonitor; import java.io.IOException; import java.nio.file.FileSystems; impo ...

  2. redis客户端修改了key-value对之后有时会报MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist o...错误,不能持久化

    解决方案,连接redis客户端 redis目录下:redis-cli -h 127.0.0.1 -p 6379-h后为redis服务器ip,-p后为端口号进入redis-client之后输入命令 co ...

  3. [loj3276]遗迹

    假设已知$a_{i}$,通过以下方式确定$b_{i}$:从后往前枚举每一个数$i$,先令$b_{i}=a_{i}$,再将$b_{i}$不断减1直至不存在$j>i$且$b_{i}=b_{j}$或$ ...

  4. 获取客户端Mac地址

    近期有个需求,需要获取客户端Mac地址作为白名单验证的依据.使用.net,B/S架构.先百度找了一些获取mac地址的方法, using System; using System.Collections ...

  5. Codeforces 587F - Duff is Mad(根号分治+AC 自动机+树状数组)

    题面传送门 第一眼看成了 CF547E-- 话说 CF587F 和 CF547E 出题人一样欸--还有另一道 AC 自动机的题 CF696D 也是这位名叫 PrinceOfPersia 的出题人出的- ...

  6. 【GWAS】如何计算显著关联位点的表型解释率PVE(phenotypic variation explained)?

    我已经通过Gemma得到了关联分析的结果,如下. prefix.log.txt 中包含了一个总的PVE,这不是我们想要的. 那么,如何计算这些位点的表型解释率? 据了解,有些关联分析软件是可以同时得到 ...

  7. Matlab矢量图图例函数quiverkey

    Matlab自带函数中不包含构造 quiver 函数注释过程,本文参照 matplotlib 中 quiverkey 函数,构造类似函数为 Matlab 中 quiver 矢量场进行标注. quive ...

  8. DIA技术及其软件工具介绍

    前言 关于蛋白质组学,你是不是已经听了太多公司的宣讲,介绍了一大堆的技术名词,反而越听越懵懂,脑袋一团乱麻?就和传话游戏一样,当我们接收了多手信息以后,得到的信息就越不准确.那么,何不自己看一看第一手 ...

  9. NFS FTP SAMBA的区别

    Samba服务 samba是一个网络服务器,用于Linux和Windows之间共享文件. samba端口号 samba (启动时会预设多个端口) 数据传输的TCP端口 139.445 进行NetBIO ...

  10. 睡眠或者重启windows,无法ssh连接或者pingVMware的虚机

    睡眠后无法直接ssh重连VMware主机问题 这个问题我在win8上出现过,win10看了下同事可以正常连,不知道其他有没有问题. 解决方法: 1.关闭vmnet8和vmnet0里面的 npcap 功 ...