【Java8新特性】四、强大的Stream api

news2025/6/19 16:38:59


这里写自定义目录标题

  • 一、了解Stream
  • 二、流(stream)到底是什么?
  • 三、Stream操作的三个步骤
  • 四、创建Stream的四种方式
  • 五、Stream 的中间操作
    • 1、筛选和切片
    • 2、map 映射
    • 3、排序
  • 六、Stream 的终止操作
    • 1、查找和匹配
    • 2、归约
    • 3、收集

一、了解Stream

Stream是Java8中处理集合的一个工具

二、流(stream)到底是什么?

流是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列

【注意】
①、Stream 自己不会存储元素
②、Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream
③、Stream操作是延迟执行的。这意味着它们会等到需要结果的时候才执行

三、Stream操作的三个步骤

  1. 创建Stream
    一个数据源(如:集合,数组),获取一个流

2)中间操作
一个中间操作链,对数据源的数据进行处理

3)终止操作
一个终止操作,执行中间操作链,并产生结果
在这里插入图片描述

四、创建Stream的四种方式

1、可以通过Collection系列集合提供的stream()或 parallelStram() 创建流

  List<String> list = new ArrayList<>();
  Stream<String> stream1 = list.stream();

2、通过Arrays中的静态方法stream()来获取数组流

  Employee[] emps = new Employee[10];
  Stream<Employee> stream2 = Arrays.stream(emps);

3、通过Stream中的静态方法 of() 创建流

 Stream<String> stream3 =  Stream.of("aa","bb","cc");

4、由函数创建流:创建无限流

Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2);
stream4.limit(10).forEach(System.out::println);


Stream<Double> s = Stream.generate(() -> Math.random());
s.limit(10).forEach(System.out::println);

五、Stream 的中间操作

【注意】多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的
处理!,而是在终止操作时一次性处理,称为“惰性求值”

1、筛选和切片

  • filter - 接受Lambda,从流中排除某些元素
  • limit - 截断流,使其元素不超过给定数量
  • skip - 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足n,则返回一个空流。
  • distinct - 筛选,通过流所生成元素的hashCode()和equals()去除重复元素
public class TestStream2 {

    List<Employee> employees = Arrays.asList(
            new Employee("张三",18,3000),
            new Employee("李四",45,4000),
            new Employee("王五",37,3000),
            new Employee("赵六",18,6000),
            new Employee("田七",40,10000),
            new Employee("田七",40,10000));

    //filter
    //内部迭代:迭代操作由Stream API完成
    @Test
    public void test1(){
        //中间操作不会不会有任何结果
        Stream<Employee> sm = employees.stream().filter((e) -> e.getAge() > 25);
        //终止操作
        //sm.forEach((e) -> System.out.println(e));
        sm.forEach(System.out::println);
    }


    //limit
    @Test
    public void test2(){
       employees.stream().filter((e) -> e.getAge() > 25)
               .limit(2).forEach(System.out::println);
    }


    //skip
    @Test
    public void test3(){
        employees.stream().filter((e) -> e.getAge() > 25)
                .skip(2).forEach(System.out::println);
    }

    //distinct() 【注意】比较的元素需要equals()方法
    @Test
    public void test4(){
        employees.stream().filter((e) -> e.getAge() > 25)
                .skip(2).distinct().forEach(System.out::println);
    }
}

2、map 映射

  • map:接收一个函数作为参数,该函数会被用到每个元素上,并将其映射成一个新的元素
  • flatMap: 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
@Test
    public void test5(){
        List<String> list = Arrays.asList("aaa","bb","ccc");
        list.stream().map((str) -> str.toUpperCase())
                .forEach(System.out::println);


        System.out.println("-----------------------------------");
        employees.stream().map(Employee::getName)
                .forEach(System.out::println);

        System.out.println("------------------------------------");
        Stream<Stream<Character>> sm = list.stream().map(TestStream2::filterCharacter);
        sm.forEach((stm) -> stm.forEach(System.out::println));

        System.out.println("------------------------------------");
        System.out.println("上述代码优化");
        list.stream().flatMap(TestStream2::filterCharacter).forEach(System.out::println);
    }

//方法:将字符串转换成一个流
public static Stream<Character> filterCharacter(String str){
    List<Character> list = new ArrayList<>();

    for(Character c: str.toCharArray()){
        list.add(c);
    }

    return list.stream();
}

3、排序

  • sorted() : 自然排序
  • sorted(Comparator com) : 定制排序
 @Test
    public void test6(){
        List<String> list = Arrays.asList("aaa","bb","ccc");
        list.stream().sorted()
                .forEach(System.out::println);

        System.out.println("------------------------------------");
        list.stream().sorted((x,y) -> -x.compareTo(y))
                .forEach(System.out::println);
    }

六、Stream 的终止操作

1、查找和匹配

allMatch - 检查是否匹配所有元素
anyMatch - 检查是否至少匹配一个元素
noneMatch - 检查是否没有匹配所有元素
findFirst - 返回第一个元素
FindAny - 返回当前流中的任意元素
count - 返回当前流中元素的总个数
max - 返回流中的最大值
min - 返回流中的最小值

public class TestStream3 {


    List<Employee> employees = Arrays.asList(
            new Employee("张三",18,3000, Employee.Status.Free),
            new Employee("李四",45,4000, Employee.Status.Free),
            new Employee("王五",37,3000, Employee.Status.Busy),
            new Employee("赵六",18,6000, Employee.Status.Vocation),
            new Employee("田七",40,10000, Employee.Status.Vocation)
    );

    /*
     查找与匹配
     allMatch - 检查是否匹配所有元素
     anyMatch - 检查是否至少匹配一个元素
     noneMatch - 检查是否没有匹配所有元素
     findFirst - 返回第一个元素
     FindAny - 返回当前流中的任意元素
     count - 返回当前流中元素的总个数
     max - 返回流中的最大值
     min - 返回流中的最小值
    */
    @Test
    public void test(){
        //allMatch
        boolean b = employees.stream()
                .allMatch((e) -> e.getStatus().equals(Employee.Status.Busy));
        System.out.println(b);

        //anyMatch
        System.out.println(employees.stream().anyMatch((e) -> e.getStatus().equals(Employee.Status.Busy)));
    
        //findFirst
        //Optional: 容器类
        Optional<Employee> op = employees.stream()
                .sorted((x, y) -> -Double.compare(x.getSalary(), y.getSalary()))
                .findFirst();
        op.orElse(new Employee());  // orElse: 如果为空,则用什么来代替
        Employee e = op.get();
        System.out.println(e);
    }

    @Test
    public void test1(){
        long count = employees.stream().count();
        System.out.println(count);

        Optional<Employee> max = employees.stream().max((x, y) -> -Double.compare(x.getSalary(), y.getSalary()));
        System.out.println(max.get());


        //最少的工资是多少
        Optional<Double> min = employees.stream()
                .map(Employee::getSalary)
                .min(Double::compare);
        System.out.println(min.get());
    }
}

2、归约

reduce(T identity,BinaryOperater) / reduce(BinaryOperater): 可以将流中元素反复结合起来,得到一个值。返回 T

public void test(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);

        //0称之为起始元素,将0作为x,在流中取出一个元素作为y,
        //然后将相加的结果作为x,再从流中取出一个元素作为y相加...
        //一直到流中的元素全部加完
        Integer sum = list.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println(sum);

        System.out.println("------------------------------");
        //获取当前公司中,工资的总和
        Double sumSalary = employees.stream()
                .map(Employee::getSalary)
                .reduce(0d, (x, y) -> x + y);
        System.out.println(sumSalary);
    }

3、收集

collect(Collector c)
collect - 将流转换成其他形式,接受一个Collector接口的实现,
用于给stream中元素做汇总的方
Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到List,Set,Map)
但是Collectors实用类提供了很多静态方法,可以方便地创建常用收集器实例,具体方法和实例如下demo:

/**
 * @author houChen
 * @date 2021/1/1 9:32
 * @Description:
 *
 *
 * 收集
 * collect - 将流转换成其他形式,接受一个Collector接口的实现,
 * 用于给stream中元素做汇总的方法
 */
public class TestStream4 {

    List<Employee> employees = Arrays.asList(
            new Employee("张三",18,3000, Employee.Status.Free),
            new Employee("李四",45,4000, Employee.Status.Free),
            new Employee("王五",37,3000, Employee.Status.Busy),
            new Employee("赵六",18,6000, Employee.Status.Vocation),
            new Employee("田七",40,10000, Employee.Status.Vocation)
    );


    @Test
    public void test2(){
        List<String> names = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toList());

        for (String name: names) {
            System.out.println(name);
        }

        System.out.println("-------------------------------------------");
        //将结果收集到特殊的集合中
        HashSet<String> set = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.toCollection(HashSet::new));
        set.forEach(System.out::println);
    }


    @Test
    public void test3(){
        //总数
        Long count = employees.stream()
                .collect(Collectors.counting());
        System.out.println(count);

        System.out.println("---------------------------------");
        //求平均年龄
        Double avgAge = employees.stream()
                .collect(Collectors.averagingDouble(Employee::getAge));
        System.out.println(avgAge);

        System.out.println("---------------------------------");
        //总和
        Double sumSalary = employees.stream()
                .collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(sumSalary);

        //最大值
        Optional<Employee> maxSalary = employees.stream()
                .collect(Collectors.maxBy((x, y) -> Double.compare(x.getSalary(), y.getSalary())));
        System.out.println(maxSalary.get());
    }

    //分组
    @Test
    public void test4(){
        Map<Employee.Status, List<Employee>> map = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus));

        Set<Employee.Status> statuses = map.keySet();
        Iterator<Employee.Status> iterator = statuses.iterator();
        while (iterator.hasNext()){
            Employee.Status next = iterator.next();
            System.out.println(next+":"+map.get(next));
        }
    }

    //多级分组 : 先按照状态分组,再按照青年、老年分组
    @Test
    public void test5(){
        Map<Employee.Status, Map<String, List<Employee>>> maps = employees.stream()
                .collect(Collectors.groupingBy(Employee::getStatus,
                        Collectors.groupingBy((e) -> {
                            if (((Employee) e).getAge() <= 35) {
                                return "青年";
                            } else {
                                return "老年";
                            }
                        })));
        System.out.println(maps);
    }

    //分区:
    //   满足条件的为一个区
    //   不满足条件的为一个区
    @Test
    public void test6(){
        Map<Boolean, List<Employee>> map = employees.stream()
                .collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
        System.out.println(map);
    }
    
    //将员工所有的名字取出来,并用"," 分隔
    @Test
    public void test7(){
        String namestr = employees.stream()
                .map(Employee::getName)
                .collect(Collectors.joining(","));
        System.out.println(namestr);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1585113.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Locust分布式压力测试】

Locust分布式压力测试 https://docs.locust.io/en/stable/running-distributed.html Distributed load generation A single process running Locust can simulate a reasonably high throughput. For a simple test plan and small payloads it can make more than a thousan…

08 - 镜像管理之:镜像仓库harbor介绍

本文参考&#xff1a;原文1 1 Harbor仓库介绍 Docker容器应用的开发和运行离不开可靠的镜像管理&#xff0c;虽然Docker官方也提供了公共的镜像仓库&#xff0c;但是从安全和效率等方面考虑&#xff0c;部署我们私有环境内的Registry 也是非常必要的。 之前介绍了Docker私有仓…

CSS - 你实现过宽高自适应的正方形吗

难度 难度级别:中高级及以上 提问概率:80% 宽高自适应的需求并不少见,尤其是在当今流行的大屏系统开发中更是随处可见,很显然已经超越了我们日常将div写死100px这样的范畴,那么如何实现一个宽高自适应的正方形呢?这里提出两种实现方案。…

pygame旋转角度发射射线

self.x self.x math.cos(math.radians(self.xuanzhuanjiao)) * 70 self.y self.y - math.sin(math.radians(self.xuanzhuanjiao)) * 70 旋转角度&#xff0c;70是间隔 间隔太小会卡 import pygame from pygame.locals import * import sys import mathpygame.init()width, …

SpringCloudAlibaba-整合sleuth和zipkin(六)

目录地址&#xff1a; SpringCloudAlibaba整合-CSDN博客 一、整合sleuth 1.引入依赖 在需要追踪的微服务中引入依赖&#xff0c;user、order、product <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter…

摩尔信使MThings之数据网关:Modbus转MQTT

由于现场设备和物联网云平台采用了不同的通信协议&#xff0c;而为了实现它们之间的互操作性和数据交换&#xff0c;需要进行协议转换。 MQTT作为一种轻量级的、基于发布/订阅模式的通信协议&#xff0c;适用于连接分布式设备和传感器网络&#xff0c;而MODBUS协议则常用于工业…

位图布隆过滤器的原理及实现

目录 位图的概念&#xff1a; 位图的前置知识&#xff1a;位运算 位图的实现&#xff1a; 位图的基本参数和构造方法&#xff1a; 位图的插入&#xff1a; 位图的查找&#xff1a; 位图的删除&#xff1a; 布隆过滤器概念&#xff1a; 布隆过滤器的实现&#xff1a; …

ThinkPHP审计(1) 不安全的SQL注入PHP反序列化链子phar利用简单的CMS审计实例

ThinkPHP代码审计(1) 不安全的SQL注入&PHP反序列化链子phar利用&简单的CMS审计实例 文章目录 ThinkPHP代码审计(1) 不安全的SQL注入&PHP反序列化链子phar利用&简单的CMS审计实例一.Thinkphp5不安全的SQL写法二.Thinkphp3 SQL注入三.Thinkphp链5.1.x结合phar实现…

基于springboot+vue+Mysql的线上教学平台

开发语言&#xff1a;Java框架&#xff1a;springbootJDK版本&#xff1a;JDK1.8服务器&#xff1a;tomcat7数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/ideaMaven包&#xff1a;…

【C++题解】1329. 求梯形的面积

问题&#xff1a;1329. 求梯形的面积 类型&#xff1a;基本运算、小数运算 题目描述&#xff1a; 梯形面积的求解公式为S(ab)h/2 。从键盘读入一个梯形的上底 a、下底 b 和高 h &#xff0c;请计算表梯形的面积。&#xff08;结果保留1位小数&#xff09;。&#xff08;5.1.1…

企业加密软件好用的有哪些?电脑文件安全守护不容错过

近年来泄密问题频发&#xff0c;重要数据外泄造成公司损失&#xff0c;越来越多的企业开始使用防泄密软件&#xff0c;来保护公司内部数据安全&#xff0c;防止信息泄露的问题出现&#xff0c;维护公司权益。那么&#xff0c;既然要使用防泄密软件&#xff0c;必然是要安装有用…

unity数组

数组的定义 动态初始化:在定义数组时只指定数组的长度&#xff0c;由系统自动为元素赋初值的方式。 静态初始化:定义数组的同时就为数组的每个元素赋值 数组的静态初始化有两种方式 1、类型门数组名new 类型[]{元素&#xff0c;元素&#xff0c;…}; 2、类型[数组名{元素&am…

股票高胜率的交易法则是什么?

股票交易中的高胜率交易法则并非一成不变&#xff0c;而是根据市场状况、个人投资风格和经验等多种因素综合而定的。以下是一些有助于提升交易胜率的法则和策略&#xff1a; 1.趋势跟踪法则&#xff1a;在股票交易中&#xff0c;趋势跟踪是一种有效的策略。通过观察大盘和个股…

前端学习<四>JavaScript基础——16-内置对象:Number和Math

内置对象 Number 的常见方法 Number.isInteger() 判断是否为整数 语法&#xff1a; 布尔值 Number.isInteger(数字); toFixed() 小数点后面保留多少位 语法&#xff1a; 字符串 myNum.toFixed(num); 解释&#xff1a;将数字 myNum 的小数点后面保留 num 位小数&#xff…

Redis从入门到精通(九)Redis实战(六)基于Redis队列实现异步秒杀下单

↑↑↑请在文章开头处下载测试项目源代码↑↑↑ 文章目录 前言4.5 分布式锁-Redisson4.5.4 Redission锁重试4.5.5 WatchDog机制4.5.5 MutiLock原理 4.6 秒杀优化4.6.1 优化方案4.6.2 完成秒杀优化 4.7 Redis消息队列4.7.1 基于List实现消息队列4.7.2 基于PubSub的消息队列4.7.…

中国独立开发者项目列表

1. 为什么有这个表 作为开发者其实比较好奇其他人在做什么业余项目(不管目的是做到盈利/玩票/试试看) 所以特意建了这个库。欢迎各位开发者把自己的项目加进来~ 发 Pull Request 或 Issue 即可 (入选标准:必须是网站或App,不能是开发者工具或论坛型网站) 地址:GitHub - …

C++ | Leetcode C++题解之第22题括号生成

题目&#xff1a; 题解&#xff1a; class Solution { public:vector<string> res; //记录答案 vector<string> generateParenthesis(int n) {dfs(n , 0 , 0, "");return res;}void dfs(int n ,int lc, int rc ,string str){if( lc n && rc n…

iOS file not found

情况1&#xff1a; framework中import其他framework时报file not found的错误 解决办法&#xff1a;framework search path 和 header search path 拖入其他.a或者.framework的存放路径&#xff0c;让当前的framework通过路径可以找到引用的.a或者.framework即可

只为兴趣,2024年你该学什么编程?

讲动人的故事,写懂人的代码 当你想学编程但不是特别关心找工作的时候,选哪种语言学完全取决于你自己的目标、兴趣和能找到的学习资料。一个很重要的点,别只学一种语言啊!毕竟,"门门都懂,样样皆通",每种编程语言都有自己的优点和适合的用途,多学几种可以让你的…

C:数据结构之链栈(不带头)

目录 前序 准备工作 函数声明 函数接口 1.初始化 2.创造节点 3. 判断栈空 4.入栈 5.出栈 6.取栈顶元素 7.销毁栈 8. 获取栈的元素个数 总结 前序 链栈是基于单链表实现的,其实栈更加适合使用顺序表来实现的,这篇文章我们来探讨一下链栈的实现。 准备工作 老规…