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

news/2024/4/29 12:50:05/文章来源:https://blog.csdn.net/hc1285653662/article/details/137610926


这里写自定义目录标题

  • 一、了解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完成@Testpublic 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@Testpublic void test2(){employees.stream().filter((e) -> e.getAge() > 25).limit(2).forEach(System.out::println);}//skip@Testpublic void test3(){employees.stream().filter((e) -> e.getAge() > 25).skip(2).forEach(System.out::println);}//distinct() 【注意】比较的元素需要equals()方法@Testpublic void test4(){employees.stream().filter((e) -> e.getAge() > 25).skip(2).distinct().forEach(System.out::println);}
}

2、map 映射

  • map:接收一个函数作为参数,该函数会被用到每个元素上,并将其映射成一个新的元素
  • flatMap: 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
@Testpublic 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) : 定制排序
 @Testpublic 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 - 返回流中的最小值*/@Testpublic void test(){//allMatchboolean b = employees.stream().allMatch((e) -> e.getStatus().equals(Employee.Status.Busy));System.out.println(b);//anyMatchSystem.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);}@Testpublic 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));@Testpublic 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);}@Testpublic 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());}//分组@Testpublic 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));}}//多级分组 : 先按照状态分组,再按照青年、老年分组@Testpublic 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);}//分区://   满足条件的为一个区//   不满足条件的为一个区@Testpublic void test6(){Map<Boolean, List<Employee>> map = employees.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));System.out.println(map);}//将员工所有的名字取出来,并用"," 分隔@Testpublic void test7(){String namestr = employees.stream().map(Employee::getName).collect(Collectors.joining(","));System.out.println(namestr);}
}

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

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HiveSQL如何生成连续日期剖析

HiveSQL如何生成连续日期剖析 情景假设&#xff1a; 有一结果表&#xff0c;表中有start_dt和end_dt两个字段&#xff0c;&#xff0c;想要根据开始和结束时间生成连续日期的多条数据&#xff0c;应该怎么做&#xff1f;直接上结果sql。&#xff08;为了便于演示和测试这里通过…

MongoDB初探:安装与图形化界面保姆级使用指南

文章目录 前言一、MongoDB下载安装下载解压配置环境变量打开mongoDB 二、配置本地MongoDB服务创建文件下载服务测试服务 三、图形化界面Compass GUINavicat GUI 总结 前言 MongoDB是一种流行的开源、面向文档的NoSQL数据库程序。与传统的关系型数据库不同&#xff0c;MongoDB将…

C# Solidworks二次开发:六种配合方式以及注意事项API详解

今天要写的文章是关于配合的一些API介绍。 如果大家还不知道创建配合的API用的是哪个&#xff0c;可以看一下我之前写的文章&#xff1a;C# Solidworks二次开发&#xff1a;创建距离配合以及移动组件API详解_solidworks transform2-CSDN博客 &#xff08;1&#xff09;今天要…

企业常用Linux文件命令相关知识+小案例

远程连接工具无法连接VMWARE&#xff1a; 如果发现连接工具有时连不上&#xff0c;ip存在&#xff0c;这时候我们查看网络编辑器&#xff0c;更多配置&#xff0c;看vnet8是不是10段&#xff0c;nat设置是否是正确的&#xff1f; 软件重启一下虚机还原一下网络编辑器 查看文件…

安卓java打包uniapp原生插件 和 uniapp使用安卓android原生插件

1.uniapp dcloud官方文档 简介 | uni小程序SDK 2.前提&#xff0c;需要有经验的安卓java开发人员&#xff0c;并且同时具备uniapp移动端开发经验。说明&#xff1a;android打包的.aar和uniapp需要的.aar是不一样的&#xff0c;uniapp需要的.aar是需要有一些特定配置的&#x…

vscode为什么设置不了中文?

VSCode中文插件安装 在VSCode中设置中文的首要步骤是安装“Chinese (Simplified) Language Pack for Visual Studio Code”扩展插件。这一过程十分简单&#xff0c;只需打开VSCode&#xff0c;进入扩展市场&#xff0c;搜索“ Chinese (Simplified) Language Pack ”然后点击…

linux进阶篇:磁盘管理(一):LVM逻辑卷基本概念及LVM的工作原理

Linux磁盘管理(一)&#xff1a;LVM逻辑卷基本概念及LVM的工作原理 一、传统的磁盘管理 在传统的磁盘管理方案中&#xff0c;如果我们的磁盘容量不够了&#xff0c;那这个时候应该要加一块硬盘&#xff0c;但是新增加的硬盘是作为独立的文件系统存在的&#xff0c;原有的文件系…

8卡微调Grok-1实战教程

本文是根据魔搭社区推出的轻量级训练推理工具SWIFT微调实战教程。SWIFT&#xff08;Scalable lightWeight Infrastructure for Fine-Tuning&#xff09;是一套基于PyTorch的轻量级、开箱即用的模型微调、推理框架&#xff0c;让AI爱好者能够轻松地在消费级显卡上运行大模型和AI…

LeetCode 热题 100 题解(二):双指针部分(2)| 滑动窗口部分(1)

题目四&#xff1a;接雨水&#xff08;No. 43&#xff09; 题目链接&#xff1a;https://leetcode.cn/problems/trapping-rain-water/description/?envTypestudy-plan-v2&envIdtop-100-liked 难度&#xff1a;困难 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&am…

基于Swin Transformers的乳腺癌组织病理学图像多分类

乳腺癌的非侵入性诊断程序涉及体检和成像技术&#xff0c;如乳房X光检查、超声检查和磁共振成像。成像程序对于更全面地评估癌症区域和识别癌症亚型的敏感性较低。 CNN表现出固有的归纳偏差&#xff0c;并且对于图像中感兴趣对象的平移、旋转和位置有所不同。因此&#xff0c;…

如何注册midjourney账号

注册Midjourney账号比较简单&#xff0c;准备好上网工具&#xff0c;进入官网 Midjourney访问地址&#xff1a; https://www.midjourney.com/ 目前没有免费使用额度了&#xff0c;会员最低 10 美元/月&#xff0c;一般建议使用30美元/月的订阅方案。了解如何订阅可以查看订阅…

无人机/飞控--ArduPilot、PX4学习记录(5)

这几天看dronekit&#xff0c;做无人机失控保护。 PX4官网上的经典案例&#xff0c;我做了很多注解&#xff0c;把代码过了一遍。 无人机具体执行了&#xff1a; 先起飞&#xff0c;飞至正上空10m->向北移动10m->向东移动10m->向南移动10m->向西移动10m->回到初…

milvus search api的数据结构

search api的数据结构 此api的功能是向量相似度搜索(vector similarity search) 一个完整的search例子: 服务端collection是一个hnsw类型的索引。 import random from pymilvus import (connections,Collection, )dim 128if __name__ __main__:connections.connect(alias…

springboot websocket 持续打印 pod 日志

springboot 整合 websocket 和 连接 k8s 集群的方式参考历史 Java 专栏文章 修改前端页面 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>Java后端WebSocket的Tomcat实现</title><script type"text/javasc…

A股企业数据要素利用水平数据集(2001-2022年)

参照史青春&#xff08;2023&#xff09;的做法&#xff0c;团队对上市公司-数据要素利用水平进行测算。统计人工智能技术、区块链技术、云计算技术、大数据技术、大数据技术应用五项指标在企业年报中的披露次数&#xff0c;求和后衡量数据要素投入水平。 一、数据介绍 数据名…

贪心算法|1005.K次取反后最大化的数组和

力扣题目链接 class Solution { static bool cmp(int a, int b) {return abs(a) > abs(b); } public:int largestSumAfterKNegations(vector<int>& A, int K) {sort(A.begin(), A.end(), cmp); // 第一步for (int i 0; i < A.size(); i) { // 第二步if…

力扣HOT100 - 56. 合并区间

解题思路&#xff1a; class Solution {public int[][] merge(int[][] intervals) {// 先按照区间起始位置排序Arrays.sort(intervals, (v1, v2) -> v1[0] - v2[0]);int[][] res new int[intervals.length][2];int idx -1;for (int[] interval : intervals) {//直接加入的…

PCF8591(ADDA转换芯片)

工具 1.Proteus 8 仿真器 2.keil 5 编辑器 原理图 讲解 PCF8591是一个单片集成、单独供电、低功耗、8-bit CMOS数据获取器件。PCF8591具有4个模拟输入、1个模拟输出和1个串行IC总线接口。PCF8591的3个地址引脚A0, A1和A2可用于硬件地址编程&#xff0c;允许在同个I2C总线上接…

【实战解析】YOLOv9全流程训练至优化终极指南

【实战解析】YOLOv9全流程训练至优化终极指南 0.引言1.环境准备2.数据预处理&#xff08;1&#xff09;数据准备&#xff08;2&#xff09;按比例划分数据集&#xff08;3&#xff09;xml转txt脚本&#xff08;4&#xff09;配置文件 3.模型训练&#xff08;1&#xff09;单GPU…

【UE5 C++】各个头文件的含义

#pragma once 预处理程序指令 作用&#xff1a;保护同一个文件不会被多次包含&#xff0c;使得头文件只会被编译一次&#xff0c; #include “CoreMinimal.h” 包含了一套来自UE4的核心编程环境的普遍存在类型 #include “GameFramework/GameModeBase.h” 基于GameModeBas…