当前位置: 首页 > news >正文

Java——Stream流的学习

在开发过程中,经常或忽略流的使用,导致用的不熟练,于是抽时间系统的学习下stream的使用,找了哔哩哔哩的教程跟着看看练练。

准备工作

创建Book、Aurhor实体类,初始化数据

public static List<Author> getAuthors() {Author author1 = new Author(1L, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);Author author2 = new Author(2L, "亚拉索", 15, "狂风也追逐不上他的思考速度", null);Author author3 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);Author author4 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);List<Book> books1 = new ArrayList<>();List<Book> books2 = new ArrayList<>();List<Book> books3 = new ArrayList<>();books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱情"));books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何成功"));books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));books2.add(new Book(4L, "吹或不吹", "爱情,个人传记", 65, "一个哲学家的恋爱观注定很难"));books3.add(new Book(5L, "你的剑就是我的剑", "爱情", 56, "无法想象一个武者"));books3.add(new Book(5L, "风与剑", "个人传记", 100, "两个哲学家灵魂与肉体的碰撞"));books3.add(new Book(5L, "风与剑", "个人传记", 100, "两个哲学家灵魂与肉体的碰撞"));author1.setBooks(books1);author2.setBooks(books2);author3.setBooks(books3);author4.setBooks(books3);List<Author> authors = new ArrayList<>(Arrays.asList(author1, author2, author3, author4));return authors;}

创建流

// 1.单列集合
private static void test01(List<Author> authors) {authors.stream().distinct().filter(author -> author.getAge()<18).forEach(author -> System.out.println(author.getName()));
}
// 2.数组流
private static void test02() {Integer[] arr = {1,2,3,4,5};
//  IntStream stream = Arrays.stream(arr);Stream<Integer> stream = Stream.of(arr);stream.distinct().filter(value -> value > 2).forEach(value -> System.out.println(value));
}
// 3.双列集合   map流
private static void test03() {Map<String, Integer> map = new HashMap<>();map.put("张三", 18);map.put("李四", 33);map.put("王五", 25);Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();stream.filter(entry -> entry.getValue()>20).forEach(entry -> System.out.println(entry.getKey()));
}

中间操作

  • filter 对流中的操作进行过滤,符合条件的返回
    使用的函数式接口是:Predicate,参数是一个实体,拥有抽象方法:boolean test(T t);
authors.stream().filter(new Predicate<Author>() {@Override// 匿名内部类的test方法,将传入的author进行判断,返回符合条件的public boolean test(Author author) {return author.getName().length() > 1;}
}).forEach(author -> System.out.println(author.getName()));

该操作将作者名字长度>1 的作者名列出来

  • map 把流中元素进行计算或转换
    使用的函数式接口是:Function<T, R>,参数是一个实体,和一个要将实体转化的结果result,拥有抽象方法:R apply(T t);
    (1)进行转换,该操作将作者名字列出来
private static void test05(List<Author> authors) {authors.stream().map(new Function<Author, String>() {@Override// 匿名内部类的apply方法,将传入的author进行需要的结果返回public String apply(Author author) {return author.getName();}}).forEach(s -> System.out.println(s));
}

(2)进行计算,该操作将作者年龄分别+10

authors.stream().map(author -> author.getAge()).map(new Function<Integer, Integer>() {@Overridepublic Integer apply(Integer age) {return age + 10;}}).forEach(s -> System.out.println(s));

第一个map是获取作者的年龄,然后第二个map则将年龄转换为年龄,只是经过了+10计算,我们打断点看看
在这里插入图片描述
流经过第一个map后转换为了Integer
在这里插入图片描述
经过第二个map后将第一个Integer进行+10计算,类型不变

  • distinct 将元素进行去重操作
    注意:distinct 依赖Object 的equals方法来判断对象是否相同,对象要重写equals方法。
authors.stream().distinct().forEach(author -> { System.out.println(author.getName()); });

该操作直接通过distinct去重
当然也可以使用前面的map提取出名字,再去重,比上面的麻烦些

authors.stream().distinct().map(new Function<Author, String>() {@Overridepublic String apply(Author author) {return author.getName();}}).forEach(name -> { System.out.println(name); });// 一样
authors.stream().distinct().map(author -> author.getName()).forEach(name -> { System.out.println(name); });

该操作先使用map将Author对象转换为姓名的String,然后在去重

  • flatMap
    上面的Map是把一个对象转换成另一个对象作为流中的元素,而flatMap是把一个对象转换为多个对象作为流中的元素

使用的函数式接口是:new Function<T, R>,将一个对象转换成Stream对象

(1)打印所有书籍的名字,要求对重复的元素进行去重。

authors.stream().flatMap(new Function<Author, Stream<Book>>() {// 这里可以通过idea进行lambda转换,为了清晰就不转了@Overridepublic Stream<Book> apply(Author author) {return author.getBooks().stream();}}).distinct().forEach(name -> { System.out.println(name); });

如果使用Map,将作者对象提取出书籍对象,还需要再对书籍对象List进行遍历去重,比较麻烦。
首先使用flatMap将每个作者对象中的书籍对象流提取出来,然后直接在书籍对象流中进行去重,输出书籍名称。
在这里插入图片描述
在这里插入图片描述
(2)打印现有数据的所有分类,要求对分类进行去重,不能出现这种格式:哲学,爱情,需要转成两个分类

authors.stream().flatMap(author -> author.getBooks().stream()).distinct()// 将分类进行分割成数组后,转成流进行去重.flatMap(book -> Arrays.stream(book.getCategory().split(","))).distinct().forEach(category -> System.out.println(category));

在这里插入图片描述
第一次使用flatmap将作者对象转换成多个书籍对象流
在这里插入图片描述

第二次使用flatmap将书籍对象的分类转换成多个分类流

终结操作

  • forEach 对流中元素进行遍历操作
  • count 获取当前流中元素的个数
    (1)打印这些作家所出书籍的数目,注意删除重复元素
    因为count属于终结操作,会有返回值
long count = authors.stream().flatMap(author -> author.getBooks().stream()).distinct().count();
System.out.println("书籍count = " + count);

在这里插入图片描述
使用flatMap获取每个书籍对象,去重计算
在这里插入图片描述

  • min和max 求流中的最值
    (1)获取这些作家的所出书籍的最高分和最低分
Optional<Integer> max = authors.stream().flatMap(author -> author.getBooks().stream()).map(book -> book.getScore()).max(new Comparator<Integer>() {@Overridepublic int compare(Integer score1, Integer score2) {return score1 - score2;}});
System.out.println("书籍评分max = " + max.get());Optional<Integer> min = authors.stream().flatMap(author -> author.getBooks().stream()).map(book -> book.getScore()).min(new Comparator<Integer>() {@Overridepublic int compare(Integer score1, Integer score2) {return score1 - score2;}});
System.out.println("书籍评分min = " + min .get());

先使用flatMap将作者对象转换成多个书籍对象流,然后用map获取书籍对象中的评分对象,进行max和min计算

  • collect 把当前流转换成一个集合
    (1)获取一个存放所有作者名字的List集合
List<String> list = authors.stream().map(author -> author.getName()).distinct().collect(Collectors.toList());System.out.println("list = " + list);

(2)获取一个所有书名的set集合

Set<String> set = authors.stream().flatMap(author -> author.getBooks().stream()).map(book -> book.getName()).collect(Collectors.toSet());System.out.println("set = " + set);

(3)获取一个map集合,key为作者名,value为List

Map<String, List<Book>> map = authors.stream()// 去重避免key重复.distinct().collect(Collectors.toMap(new Function<Author, String>() {@Override // 这里的匿名内部类将传入作者对象,获取作者名作为keypublic String apply(Author author) { return author.getName(); }}, new Function<Author, List<Book>>() {@Override // 这里的匿名内部类将传入作者对象,获取书籍list作为valuepublic List<Book> apply(Author author) { return author.getBooks(); }}));System.out.println("map = " + map);

简化lambda表达式

Map<String, List<Book>> map = authors.stream()// 去重避免key重复.distinct().collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));System.out.println("map = " + map);
  • anyMatch 判断流中是否有任意符合匹配条件的元素,符合返回true
boolean b = authors.stream().anyMatch(author -> author.getAge() > 29);System.out.println("b = " + b);

判断是否有年龄在29以上的作家

  • allMatch 判断流中元素是否都符合条件,都符合为true,否则为false
boolean b = authors.stream().allMatch(author -> author.getAge() >= 18);
System.out.println("b = " + b);

判断是否所有作家都是成年人

  • noneMatch 判断流中元素是否都不符合条件,是为true,否为false
boolean b = authors.stream().noneMatch(author -> author.getAge() > 100);
System.out.println("b = " + b);

判断作家是否都没有超过100岁的

  • findAny 获取流中符合条件的任意一个元素,不保证为流中的第一个元素
Optional<Author> au = authors.stream().filter(author -> author.getAge() > 18).findAny();System.out.println("名字:" + au.get().getName());

这里用的get方法获取数据,但是可能出现找不到符合条件的数据,这时候get就会报错,如:
在这里插入图片描述
所以改成:

Optional<Author> au = authors.stream().filter(author -> author.getAge() > 98).findAny();au.ifPresent(author -> System.out.println(author.getName()));

获取任意一个大于18的作家,输出名字

  • findFirst 获取流中的第一个元素
Optional<Author> author = authors.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).findFirst();author.ifPresent(author1 -> System.out.println(author1.getName()));

获取年龄最小的作家,输出名字

  • reduce归并 对流中的数据按照指定的计算方式计算出一个结果(缩减操作)
    把stream中的元素组合起来,传入初始化值,按照指定的计算方式和元素进行计算,计算结果再和下一个元素进行计算,依次计算完

reduce有三种重载方式

  1. 2个参数的
    T reduce(T identity, BinaryOperator accumulator);
T result = identity;
for (T element : this stream) {result = accumulator.apply(result, element)
}
return result;

传入初始化值作为第一个参数identity,传入计算方法accumulator.apply 进行初始化值和元素的计算

例子:
(1)使用reduce对作者年龄进行求和

Integer result = authors.stream().distinct().map(author -> author.getAge())// 传入初识值和计算方法.reduce(0, new BinaryOperator<Integer>() {@Overridepublic Integer apply(Integer result, Integer element) {return result + element;}});System.out.println("result = " + result);

lambda写

Integer result = authors.stream().distinct().map(author -> author.getAge())// 传入初识值和计算方法.reduce(0, (result1, element) -> result1 + element);System.out.println("result = " + result);

(2)使用reduce求所有作者年龄最大值

Integer max = authors.stream().distinct().map(author -> author.getAge()).reduce(Integer.MIN_VALUE, new BinaryOperator<Integer>() {@Overridepublic Integer apply(Integer result, Integer element) {return result > element ? result : element;}});
System.out.println("max = " + max);

(3)使用reduce求所有作者年龄最小值

Integer min = authors.stream().distinct().map(author -> author.getAge()).reduce(Integer.MAX_VALUE, new BinaryOperator<Integer>() {@Overridepublic Integer apply(Integer result, Integer element) {return result > element ? element : result;}});System.out.println("min = " + min);
  1. 1个参数的
    Optional reduce(BinaryOperator accumulator);
boolean foundAny = false;
T result = null;
for (T element : this stream) {if (!foundAny) {foundAny = true;result = element;} else {result = accumulator.apply(result, element);}
}return foundAny ? Optional.of(result) : Optional.empty();

该方法只传入了一个计算方式,根据实现方法,可以看到将流中的第一个元素作为了第一个元素result,然后后续进行else内部的计算

例如:

Optional<Integer> optional = authors.stream().distinct().map(author -> author.getAge())// 直接传入计算方法.reduce((result, element) -> result > element ? element : result);optional.ifPresent(integer -> System.out.println(integer));

相关文章:

  • 分享一个学英语的网站
  • 若依不分离版本部署流程
  • 【工作记录】基于docker+mysql部署单机版nacos2.0.4@20240219
  • 淘宝商品采集API通过商品id获取商品详情信息
  • 网络安全-一句话木马
  • steam搬砖项目真的假的,2024年到底还能不能做?
  • Linux——网络通信TCP通信常用的接口和tcp服务demo
  • 【springboot+vue项目(十五)】基于Oauth2的SSO单点登录(二)vue-element-admin框架改造整合Oauth2.0
  • SQL-2
  • 二、ActiveMQ安装
  • spring boot自动装配及自动装配条件判断
  • 蓝桥杯刷题--python-9(2023填空题2)
  • Stable Diffusion——基础模型、VAE、LORA、Embedding各个模型的介绍与使用方法
  • 分页工具类
  • linux系统监控工具的补充内容
  • 自己简单写的 事件订阅机制
  • Centos6.8 使用rpm安装mysql5.7
  • ES6之路之模块详解
  • gulp 教程
  • HTML中设置input等文本框为不可操作
  • iOS小技巧之UIImagePickerController实现头像选择
  • JavaScript设计模式系列一:工厂模式
  • JavaWeb(学习笔记二)
  • mysql中InnoDB引擎中页的概念
  • Next.js之基础概念(二)
  • Python学习之路13-记分
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 基于Javascript, Springboot的管理系统报表查询页面代码设计
  • 基于webpack 的 vue 多页架构
  • 问:在指定的JSON数据中(最外层是数组)根据指定条件拿到匹配到的结果
  • 一道闭包题引发的思考
  • 赢得Docker挑战最佳实践
  • 找一份好的前端工作,起点很重要
  • zabbix3.2监控linux磁盘IO
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • # Apache SeaTunnel 究竟是什么?
  • $redis-setphp_redis Set命令,php操作Redis Set函数介绍
  • (2020)Java后端开发----(面试题和笔试题)
  • (C语言)字符分类函数
  • (M)unity2D敌人的创建、人物属性设置,遇敌掉血
  • (Redis使用系列) Springboot 使用redis实现接口幂等性拦截 十一
  • (附源码)springboot课程在线考试系统 毕业设计 655127
  • (十)DDRC架构组成、效率Efficiency及功能实现
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (一)Dubbo快速入门、介绍、使用
  • (转)3D模板阴影原理
  • .a文件和.so文件
  • .net Application的目录
  • .NET CF命令行调试器MDbg入门(一)
  • .NET CORE Aws S3 使用
  • .NET Core 将实体类转换为 SQL(ORM 映射)
  • .net core 依赖注入的基本用发
  • .Net Framework 4.x 程序到底运行在哪个 CLR 版本之上
  • .Net IOC框架入门之一 Unity
  • .NET(C#、VB)APP开发——Smobiler平台控件介绍:Bluetooth组件