Stream 的终止操作

 一、规约

 * reduce(T iden, BinaryOperator b)     可以将流中元素反复结合起来,得到一个值。 返回 T
* reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。 返回 Optional<T>
public static void test02() {
//01.数值求和
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
/**
*0 是起始x,0 + y[0] 结果赋值给x, 再➕y[1] 结果再赋值给x 再➕y[2] 。。。。。。
* 因为有起始数值,所以不可能为空,所以返回值为 泛型的类型
*/ Integer reduce = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(reduce); System.out.println("--------------------"); //02.求JavaBean的工资属性求和
//没有起始值,可能为空,所以返回值类型设为了Optional,为了避免空指针异常,有可能为空的情况就用这个
Optional<Double> reduce2 = emps.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(reduce2.get()); }

二、收集

方法

描述

collect(Collector c)

将流转换为其他形式。接收一个 Collector接口的 实现,用于给Stream中元素做汇总的方法

Collector 接口中方法的实现决定了如何对流执行收集操作(如收 集到 List、Set、Map)。但是 Collectors 实用类提供了很多静态 方法,可以方便地创建常见收集器实例,具体方法与实例如下表:

/**
* 收集
*/
public static void collect() {
List<String> list = emps.stream()
.map(Employee::getName)
.collect(Collectors.toList());//Collectors.toSet();
list.forEach(System.out::println); System.out.println("----------------------"); TreeSet<String> treeSet = emps.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(TreeSet::new)); //定制化容器类 treeSet.forEach(System.out::println);
}

 三、判断性终止函数

public static void test01() {
boolean allMatch = emps.stream().allMatch(x -> x.getStatus().equals(Status.BUSY));
boolean anyMatch = emps.stream().anyMatch(x -> x.getStatus().equals(Status.BUSY));
boolean noneMatch = emps.stream().noneMatch(x -> x.getStatus().equals(Status.BUSY));
//Optional是一个新的集合类,为了防止空指针异常
Optional<Employee> first = emps.stream().sorted((x1,x2) -> Double.compare(x1.getSalary(),x2.getSalary())).findFirst();
Employee employee = first.get(); //并行执行 sorted和findAny
Optional<Employee> anyEmployeeOptional = emps.parallelStream().sorted((x1,x2) -> Double.compare(x1.getSalary(),x2.getSalary())).findAny();
Employee anyEmployee = first.get(); long count = emps.stream().count(); Optional<Employee> max = emps.stream().max((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
Employee maxSalaryEmployee = max.get(); Optional<Double> minSalary = emps.stream().map(Employee::getSalary)
.min(Double::compare);
Double maxSalary = minSalary.get(); System.out.println(allMatch);
System.out.println(anyMatch);
System.out.println(noneMatch);
System.out.println(anyEmployee);
System.out.println(first);
System.out.println(count);
System.out.println(maxSalaryEmployee);
System.out.println(minSalary);
}
 
 四、组函数
  /**
* 组函数
*/
public static void groupFunction() { //总数
long count0 = emps.stream().count();
Long count1 = emps.stream().collect(Collectors.counting()); System.out.println("总数1:" + count0);
System.out.println("总数2:" + count1); //平均值
Double avg = emps.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println("平均值:" + avg); //总和
Double collectSum = emps.stream().collect(Collectors.summingDouble(Employee::getSalary));
double reduceSum = emps.stream().mapToDouble(Employee::getSalary).reduce(0, (x, y) -> x + y);
System.out.println("总和1:" + collectSum);
System.out.println("总和2:" + reduceSum); //最大值
Optional<Double> collectMax = emps.stream().map(Employee::getSalary).collect(Collectors.maxBy((x1, x2) -> x1.compareTo(x2)));
Optional<Double> max = emps.stream().map(Employee::getSalary).max((x1, x2) -> x1.compareTo(x2)); System.out.println("最大值1:" + collectMax.get());
System.out.println("最大值2:" + max.get()); //最小值
Optional<Double> collectMin = emps.stream().map(Employee::getSalary).collect(Collectors.minBy((x1, x2) -> x1.compareTo(x2)));
Optional<Double> min = emps.stream().map(Employee::getSalary).min((x1, x2) -> x1.compareTo(x2)); System.out.println("最小值1:" + collectMin.get());
System.out.println("最小值2:" + min.get());
}
 五、分组
    /**
* 分组
*/
public static void group() {
System.out.println("按照单个字段分组-----------------");
Map<Status, List<Employee>> collectGroupMap = emps.stream().collect(Collectors.groupingBy(Employee::getStatus));
collectGroupMap.forEach((key,value) -> System.out.println(key + " | " + value)); System.out.println("\n先按单个字段分组,每个分组里面再按自定义规则分组-----------------"); Map<Status, Map<String, List<Employee>>> innerGroupMapByIdentify = emps.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy(x -> {
if (((Employee) x).getAge() < 35) {
return "青年";
} else if (((Employee) x).getAge() < 55) {
return "中年";
} else {
return "老年";
}
})));
innerGroupMapByIdentify.forEach((key,value) -> System.out.println(key + " | " + value)); System.out.println("\n先按单个字段分组,每个分组里面再按另外一字段分组-----------------");
Map<Status, Map<String, List<Employee>>> innerGroupMapByColum = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus,
Collectors.groupingBy(Employee::getName)
)
); innerGroupMapByColum.forEach((key,value) -> System.out.println(key + " | " + value)); System.out.println("\n先按2个字段一起分组-----------------");
Map<String, List<Employee>> columsMap = emps.stream()
.collect(Collectors.groupingBy(x -> ((Employee) x).getName() + " : " + ((Employee) x).getStatus().toString()));
columsMap.forEach((key,value) -> System.out.println(key + " | " + value));
}

六、分区
    /**
* 分区
*/
public static void partition() {
//一层分区
Map<Boolean, List<Employee>> partitionMap = emps.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 35));
//多层级分区,二层按照一层相同的规则分区
Map<Boolean, Map<Boolean, List<Employee>>> collect = emps.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 35, Collectors.partitioningBy(x -> x.getSalary() < 6000.0))); //多层级分区,二层按照一层不同的规则分区
Map<Boolean, Map<String, List<Employee>>> collect1 = emps.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 35, Collectors.groupingBy(Employee::getName))); partitionMap.forEach((key,value) -> System.out.println(key + " | " + value));
collect.forEach((key,value) -> System.out.println(key + " | " + value));
collect1.forEach((key,value) -> System.out.println(key + " | " + value));
}
七、字符串拼接:join 

/**
* 字符串拼接:join
*/
public static void join(){
String joinResult = emps.stream().map(Employee::getName).collect(Collectors.joining(",", " ===start=== ", " ===end=== "));
System.out.println(joinResult);
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Reduce:规约;Collector:收集、判断性终止函数、组函数、分组、分区的更多相关文章

  1. MySQL-第九篇分组和组函数

    1.组函数 组函数:即多行函数,组函数将一组记录作为整体计算,每组记录返回一个结果,而不是每条记录返回一个结果. 2.常用的组函数有: 1>avg([distinct|all]expr):计算多 ...

  2. Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)...啊啊啊

    函数式编程 函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计 ...

  3. (转)Python进阶:函数式编程(高阶函数,map,reduce,filter,sorted,返回函数,匿名函数,偏函数)

    原文:https://www.cnblogs.com/chenwolong/p/reduce.html 函数式编程 函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数 ...

  4. Firefox 对条件判断语句块内的函数声明的处理与其他浏览器有差异

    标准参考 函数声明和函数表达式 定义一个函数有两种途径:函数声明和函数表达式. 函数声明: function Identifier ( FormalParameterList opt ) { Func ...

  5. sqlserver判断是否为数字的函数

    ISNUMERIC 确定表达式是否为一个有效的数字类型. 语法  ISNUMERIC ( expression ) 参数 expression 要计算的表达式. 返回类型 int 测试: select ...

  6. (查找函数+atoi)判断与(注册函数+strcmp函数)判断两种方法

    loadrunner中接口判断的2中方法    如下: 1. ●查找函数web_reg_find() ● atoi():将字符串转换为整型值 作比较  > 0 Action() { //检查点函 ...

  7. Python_代码练习_写一个判断是否为小数的函数

    这两天在学习函数,练习写一个判断是否为小数的函数,看起来蛮简单的,飞速写完很是得意,然后测了一下,发现差得好多呀,这个并不像想象那样简单,我得到的教训是,想要把一个需求哪怕再小的需求考虑周全,都不是件 ...

  8. 【Linux编程】进程终止和exit函数

    内核要运行一个应用程序,唯一的途径是通过系统调用.exec函数.exec又会调用启动程序,启动程序(一般是汇编语言)以类似以下的方式调用main函数: void exit(main(argc, arg ...

  9. Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数

    高阶函数Higher-orderfunction 变量可以指向函数 >>> abs #abs(-10)是函数调用,而abs是函数本身 <built-in function ab ...

随机推荐

  1. 【转】Ubuntu 64位系统安装交叉编译环境一直提醒 没有那个文件或目录

    安装交叉编译环境搞了一个晚上 一直提示 root@zqs-pc:~# arm-linux-gcc/usr/local/arm/4.3.2/bin/arm-linux-gcc: 行 3: /usr/lo ...

  2. HttpWebRequest发http参数

    使用js发请求时,一般使用表单.json对象或者字符串 $.post(url,jsonStr) 服务端获取参数 Request.QueryString.Get();// GET参数 Request.F ...

  3. luogu5019 [NOIp2018]铺设道路 (贪心)

    和NOIp2013 积木大赛一模一样 我在堆一格的时候,我把它尽量地往右去延伸 于是如果对于一个i,a[i-1]<a[i],那i在之前一定只堆过a[i-1]那么多,所以要再堆a[i]-a[i-1 ...

  4. extern C小结

    名词解释 1.extern extern翻译为外部的,用在变量或函数之前,使其可见范围拓宽,这就是为啥叫extern吧.那它是用来干嘛的呢?当用在变量或函数之前,提示编译器到其他模块寻找其定义. 举个 ...

  5. kali源更新

    对于新装kali的同学一点存在着更新源的问题 这是对初次安装,进行系统更新的教程 首先需要有gpg_key wget -q -O - https://archive.kali.org/archive- ...

  6. webpack入门(二)what is webpack

    webpack is a module bundler.webpack是一个模块打包工具,为了解决上篇一提到的各种模块加载或者转换的问题. webpack takes modules with dep ...

  7. maven将项目及第三方jar打成一个jar包

    pom.xml中添加如下配置 把依赖包和自己项目的文件打包如同一个jar包(这种方式对spring的项目不支持) <build> <plugins> <plugin> ...

  8. Java Number & Math 类

    // java.lang.Math 常用 // xxxValue() 方法用于将 Number 对象转换为 xxx 数据类型的值并返回. System.out.println(((Integer) 5 ...

  9. 洛谷P3168 任务查询系统

    题意:有n个任务,第i个的存在时间是li~ri,有个权值.求t时刻第k大的权值. 这毒瘤...本来是前缀和 -> 主席树,我是树套树...然后光荣TLE. 其实很裸.一开始我写的是每个位置维护一 ...

  10. C++ 容器操作

    typedef struct point { int x; int y; }Point; 在声明变量的时候就可以:Point p1; 如果没有typedef, 如: struct point { in ...