博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java8中Stream的归约与收集
阅读量:6684 次
发布时间:2019-06-25

本文共 5512 字,大约阅读时间需要 18 分钟。

Java8中Stream的归约与收集

归约

reduce(T identity, BinaryOperator) / reduce(BinaryOperator) --可以将流中元素反复结合起来,得到一个值

public class Employee {    private String name;    private Integer age;    private Double salary;    private Status status;    public Employee() {        super();    }    public  Employee(Integer age){        this.age = age;    }    public Employee(String name, Integer age, Double salary) {        super();        this.name = name;        this.age = age;        this.salary = salary;    }    public Employee(String name, Integer age, Double salary, Status status) {        this.name = name;        this.age = age;        this.salary = salary;        this.status = status;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public double getSalary() {        return salary;    }    public void setSalary(Double salary) {        this.salary = salary;    }    public Status getStatus() {        return status;    }    public void setStatus(Status status) {        this.status = status;    }    @Override    public String toString() {        return "Employee{" +                "name='" + name + '\'' +                ", age=" + age +                ", salary=" + salary +                ", status=" + status +                '}';    }    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        Employee employee = (Employee) o;        return age == employee.age &&                Double.compare(employee.salary, salary) == 0 &&                Objects.equals(name, employee.name);    }    @Override    public int hashCode() {        return Objects.hash(name, age, salary);    }    public enum Status{        FREE,        BUSY,        VOCATION;    }}
//归约    @Test    public void test1(){        List
list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer sum = list.stream() .reduce(0, (x, y) -> x + y); System.out.println(sum);//首先把0作为x,然后从流中取出一个元素作为y,然后把运算结果作为x,再取出下一个元素作为y System.out.println("--------------------------------------"); Optional
op = employees.stream() .map(Employee::getSalary) .reduce(Double::sum); System.out.println(op.get()); }

收集

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

//收集    @Test    public void test2(){        List
list = employees.stream() .map(Employee::getName) .collect(Collectors.toList()); list.forEach(System.out::println); System.out.println("--------------------------------"); Set
set = employees.stream() .map(Employee::getName) .collect(Collectors.toSet()); set.forEach(System.out::println); System.out.println("---------------------------------"); HashSet
hs = employees.stream() .map(Employee::getName) .collect(Collectors.toCollection(HashSet::new)); hs.forEach(System.out::println); } @Test public void test3(){ //总数 Long count = employees.stream() .collect(Collectors.counting()); System.out.println(count); System.out.println("-------------------------------"); //平均值 Double avg = employees.stream() .collect(Collectors.averagingDouble(Employee::getSalary)); System.out.println(avg); System.out.println("--------------------------------"); //总和 Double sum = employees.stream() .collect(Collectors.summingDouble(Employee::getSalary)); System.out.println(sum); System.out.println("---------------------------------"); //最大值 Optional
max = employees.stream() .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(max.get()); System.out.println("---------------------------------"); //最小值 Optional
min = employees.stream() .map(Employee::getSalary) .collect(Collectors.minBy(Double::compare)); System.out.println(min.get()); } //分组 @Test public void test4(){ Map
> map = employees.stream() .collect(Collectors.groupingBy(Employee::getStatus)); System.out.println(map); } //多级分组 @Test public void test5(){ Map
>> map = employees.stream() .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> { if (((Employee) e).getAge() <= 35) { return "青年"; } else if (((Employee) e).getAge() <= 50) { return "中年"; } else { return "老年"; } }))); System.out.println(map); } //分区 @Test public void test6(){ Map
> map = employees.stream() .collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000)); System.out.println(map); } @Test public void test7(){ DoubleSummaryStatistics dss = employees.stream() .collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(dss.getSum()); System.out.println(dss.getAverage()); System.out.println(dss.getMax()); } @Test public void test8(){ String str = employees.stream() .map(Employee::getName) .collect(Collectors.joining(",", "开始", "结束")); System.out.println(str); }

转载于:https://blog.51cto.com/pengge666/2390291

你可能感兴趣的文章
鸟哥私房菜重温6
查看>>
适用于ASP等环境的JS日期选择控件
查看>>
CU3ER非常Cool的3D效果的Flash Slider
查看>>
Linux常用命令
查看>>
10、《每天5分钟玩转Docker容器技术》学习-Docker命令之本地镜像管理
查看>>
shell脚本:输出昨天的日期
查看>>
css优先级详解
查看>>
小白第三天
查看>>
2016年linux运维人员必会开源运维工具体系
查看>>
安装lenovo SR860 7x69服务器遇到的坑
查看>>
MIT透过机器学习技术用胺基酸预测蛋白质结构
查看>>
python课堂笔记之django-day01(8)
查看>>
Hadoop之HDFS分布式文件系统具有哪些优点?
查看>>
小型企业公司路由器做DHCP服务器
查看>>
愿不负青春 历经风雨 归期我们仍是少年|六一大童节
查看>>
JAVA数组和面向对象
查看>>
NVisionXR_iOS教程四 —— 在立方体上贴材质
查看>>
Microsoft Visual C++ Runtime library not enough space for thread data
查看>>
Centos 7 ntp时间服务器搭建
查看>>
电压电流采集模块,温湿度采集,称重模块,变送器,adc模数转换模块
查看>>