深入理解Java8新特性之Stream API的终止操作步骤

2022-01-24 0 425
目录

1.写在前面

承接了上一篇文章(说完了Stream API的创建方式及中间操作):深入理解Java8新特性之Stream API的创建方式和中间操作步骤。

我们都知道Stream API完成的操作是需要三步的:创建Stream → 中间操作 → 终止操作。那么这篇文章就来说一下终止操作。

2.终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。

2.1 终止操作之查找与匹配

首先,我们仍然需要一个自定义的Employee类,以及一个存储它的List集合。

在Employee类定义了枚举(BUSY:忙碌;FREE:空闲;VOCATION:休假)

package com.szh.java8;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
/**
 *
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee2 {
 
    private Integer id;
    private String name;
    private Integer age;
    private Double salary;
    private Status status;
 
    public Employee2(Integer id) {
        this.id = id;
    }
 
    public Employee2(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
 
    public enum Status {
        FREE,
        BUSY,
        VOCATION
    }
 
}
    List<Employee2> employees = Arrays.asList(
            new Employee2(1001,\"张三\",26,6666.66, Employee2.Status.BUSY),
            new Employee2(1002,\"李四\",50,1111.11,Employee2.Status.FREE),
            new Employee2(1003,\"王五\",18,9999.99,Employee2.Status.VOCATION),
            new Employee2(1004,\"赵六\",35,8888.88,Employee2.Status.BUSY),
            new Employee2(1005,\"田七一\",44,3333.33,Employee2.Status.FREE),
            new Employee2(1005,\"田七二\",44,3333.33,Employee2.Status.VOCATION),
            new Employee2(1005,\"田七七\",44,3333.33,Employee2.Status.BUSY)
    );

查找所有的员工是否都处于BUSY状态、至少有一个员工处于FREE状态、没有员工处于VOCATION状态。

    @Test
    public void test1() {
        boolean b1 = employees.stream()
                .allMatch((e) -> e.getStatus().equals(Employee2.Status.BUSY));
        System.out.println(b1);
 
        boolean b2 = employees.stream()
                .anyMatch((e) -> e.getStatus().equals(Employee2.Status.FREE));
        System.out.println(b2);
 
        boolean b3 = employees.stream()
                .noneMatch((e) -> e.getStatus().equals(Employee2.Status.VOCATION));
        System.out.println(b3);
    }

对员工薪资进行排序之后,返回第一个员工的信息; 筛选出BUSY状态员工之后,返回任意一个处于BUSY状态的员工信息。

    @Test
    public void test2() {
        Optional<Employee2> op1 = employees.stream()
                .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
                .findFirst();
        System.out.println(op1.get());
 
        System.out.println(\"----------------------------------\");
 
        Optional<Employee2> op2 = employees.stream()
                .filter((e) -> e.getStatus().equals(Employee2.Status.BUSY))
                .findAny();
        System.out.println(op2.get());
    }

下面,我们来看一下另外一组查找与匹配的方法。

计算处于VOCATION状态的员工数量;对员工薪资字段进行映射,同时获取其中的最高薪资;获取年龄最小的员工信息。

    @Test
    public void test3() {
        long count = employees.stream()
                .filter((e) -> e.getStatus().equals(Employee2.Status.VOCATION))
                .count();
        System.out.println(count);
 
        Optional<Double> op1 = employees.stream()
                .map(Employee2::getSalary)
                .max(Double::compare);
        System.out.println(op1.get());
 
        Optional<Employee2> op2 = employees.stream()
                .min((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge()));
        System.out.println(op2.get());
    }

在这里,大家需要注意的一点就是:当前Stream流一旦进行了终止操作,就不能再次使用了。

我们看下面的代码案例。(异常信息说的是:stream流已经被关闭了)

    @Test
    public void test4() {
        Stream<Employee2> stream = employees.stream()
                .filter((e) -> e.getStatus().equals(Employee2.Status.BUSY));
        long count = stream.count();
 
        stream.map(Employee2::getName);
    }

2.2 终止操作之归约与收集

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

计算整数1~10的和;对员工薪资字段进行映射,之后获取所有员工的薪资总和。

    @Test
    public void test1() {
        List<Integer> 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);
 
        System.out.println(\"-------------------------------\");
 
        Optional<Double> optional = employees.stream()
                .map(Employee2::getSalary)
                .reduce(Double::sum);
        System.out.println(optional.get());
    }

依次对我们先前定义好的存储员工信息的List集合 做name字段的映射,然后 转为 List、Set、HashSet(使用 Collectors 实用类中的静态方法即可完成)。

在Set、HashSet集合中,由于元素是无序、不可重复的,所以只有一个田七二。

    @Test
    public void test2() {
        List<String> list = employees.stream()
                .map(Employee2::getName)
                .collect(Collectors.toList());
        list.forEach(System.out::println);
 
        System.out.println(\"-------------------------------\");
 
        Set<String> set = employees.stream()
                .map(Employee2::getName)
                .collect(Collectors.toSet());
        set.forEach(System.out::println);
 
        System.out.println(\"-------------------------------\");
 
        HashSet<String> hashSet = employees.stream()
                .map(Employee2::getName)
                .collect(Collectors.toCollection(HashSet::new));
        hashSet.forEach(System.out::println);
    }

对员工薪资字段做映射,之后通过比较器获取最高薪资;

不做映射处理,直接通过比较器获取薪资最低的员工信息;

计算所有员工的薪资总和;

计算所有员工的平均薪资;

计算员工总数;

对员工薪资字段做映射,之后通过比较器获取最高薪资;

    @Test
    public void test3() {
        Optional<Double> max = employees.stream()
                .map(Employee2::getSalary)
                .collect(Collectors.maxBy(Double::compare));
        System.out.println(max.get());
 
        Optional<Employee2> min = employees.stream()
                .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(min.get());
 
        Double sum = employees.stream()
                .collect(Collectors.summingDouble(Employee2::getSalary));
        System.out.println(sum);
 
        Double avg = employees.stream()
                .collect(Collectors.averagingDouble(Employee2::getSalary));
        System.out.println(avg);
 
        Long count = employees.stream()
                .collect(Collectors.counting());
        System.out.println(count);
 
        DoubleSummaryStatistics dss = employees.stream()
                .collect(Collectors.summarizingDouble(Employee2::getSalary));
        System.out.println(dss.getMax());
    }

单个条件分组:根据员工状态对Stream流进行分组。 因为分组之后得到的是一个Map集合,key就是员工状态,value则是一个List集合。

    @Test
    public void test4() {
        Map<Employee2.Status, List<Employee2>> map = employees.stream()
                .collect(Collectors.groupingBy(Employee2::getStatus));
 
        Set<Map.Entry<Employee2.Status, List<Employee2>>> set = map.entrySet();
        Iterator<Map.Entry<Employee2.Status, List<Employee2>>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Employee2.Status, List<Employee2>> entry = iterator.next();
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
    }

多个条件分组:先按照员工状态分组,如果状态相同,再按照员工年龄分组。

    @Test
    public void test5() {
        Map<Employee2.Status, Map<String, List<Employee2>>> map = employees.stream()
                .collect(Collectors.groupingBy(Employee2::getStatus, Collectors.groupingBy((e) -> {
                    if (e.getAge() <= 35) {
                        return \"成年\";
                    } else if (e.getAge() <= 60) {
                        return \"中年\";
                    } else {
                        return \"老年\";
                    }
                })));
 
        Set<Employee2.Status> set = map.keySet();
        Iterator<Employee2.Status> iterator = set.iterator();
        while (iterator.hasNext()) {
            Employee2.Status next = iterator.next();
            Map<String, List<Employee2>> listMap = map.get(next);
            System.out.println(next);
            System.out.println(listMap);
        }
    }

根据特定的条件对员工进行分区处理。(员工薪资大于等于5000为 true 分区;否则都为 false 分区)。

    @Test
    public void test6() {
        Map<Boolean, List<Employee2>> map = employees.stream()
                .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
        map.forEach((key,value) -> System.out.println(\"键:\" + key + \", 值:\" + value));
    }

以上就是深入理解Java8新特性之Stream API的终止操作步骤的详细内容,更多关于Java8 Stream API 终止操作的资料请关注其它相关文章!

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 深入理解Java8新特性之Stream API的终止操作步骤 http://www.20zxx.cn/297574/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务