Stream流的使用

转换为流的操作

map转换为stream流

Map map = new HashMap();
Set<Map.Entry<String,Integer>> set = map.entrySet();
Stream<Map.Entry<String,Integer>> stream = set.stream();

数组转换为Stream流

Integer [] arr = {1,2,3,4,5,4};
Stream<Integer> stream = Stream.of(arr);

list转换为stream流

List list = new ArrayList();
Stream stream = list.stream();

流的中间操作

对于集合数据的操作

filter:用于过滤掉匹配条件数据

List<Author> authors = getAuthors();
authors.stream()
.filter(author -> author.getName().length() > 1) //名字长度大于1的过滤掉
.forEach(author -> System.out.println(author.getName()));

filter过滤多个条件使用and

List<Author> authors = getAuthors();
authors.stream()
.filter(((Predicate<Author>) author -> author.getAge() > 17).and(author -> author.getName().length() > 1))
.forEach(author -> System.out.println(author.getName()));

map:用于数据转换

List<Author> authors = getAuthors();
authors.stream()
.map(author -> author.getAge()) //将List的数据转换为 Integer
.map(age -> age+10) //给integer加10
.forEach(age -> System.out.println(age));//终结操作

distinct:去重操作

List<Author> authors = getAuthors();
authors.stream()
.distinct() //去除重复的数据
.forEach(author -> System.out.println(author.getName()));

sorted:排序操作

List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.sorted((o1,o2) -> o1.getAge() - o2.getAge()) //第一个参数减第二个参数升序,反过来就是降序
.forEach(author -> System.out.println(author.getAge()));

limit:限制数据长度

List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.sorted() //如果不填写参数默认使用实体类中compareTo方法排序
.limit(1) //展示一条数据
.forEach(author -> System.out.println(author.getName()));

skip:跳过几个元素

List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.sorted() //排序
.skip(2) //跳过两个元素,例如1,2,3三个数据跳过两个只输出 3
.forEach(author -> System.out.println(author.getAge()));

flagMap:可以转换多个对象,map只能转换单个对象

List<Author> authors = getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())//获取到集合对象转换为流
.distinct() //给第一次转换完成的结果去重
.flatMap(book -> Arrays.stream(book.getCategory().split(","))) //获取book对象中的类别字段,将 值一,值二这种类型的数据转换为数组在转换为流
.distinct() //给第二次转换完成的结果去重
.forEach(s -> System.out.println(s));

终结操作

操作stream流,使用完成后必须需要终结操作,否则无效,终结操作之后不可以在去.中间操作

forEach:负责遍历输出数据

List<Author> authors = getAuthors();
authors.stream()
.distinct() //去重
.sorted() //排序
.forEach(author -> System.out.println(author)); //遍历输出结果

count:获取个数 有返回值

List<Author> authors = getAuthors();
long count = authors.stream()
.flatMap(author -> author.getBooks().stream()) //将authors流对象转换为book流对象
.distinct() //去重
.count(); //获取返回的个数,需要用一个变量接收。
System.out.println(count);

max,min:获取最大最小值

Optional对象 https://www.cnblogs.com/zjh0420/p/16677938.html

List<Author> authors = getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.map(book -> book.getScore())
.max((o1, o2) -> o1 - o2); //获取最大值 System.out.println(max.get());

collect:把当前流转换成一个集合

List<Author> authors = getAuthors();
//转换为一个新的list集合
List<String> collect = authors.stream()
.map(author -> author.getName())
.collect(Collectors.toList());
System.out.println(collect); //转换为一个新的Set集合
Set<Book> collect = authors.stream()
.flatMap(author -> author.getBooks().stream())
.collect(Collectors.toSet());
System.out.println(Arrays.asList(collect)); //转换为一个新的Mapp集合
List<Author> authors = getAuthors();
Map<String, List<Book>> collect = authors.stream()
.distinct()
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
System.out.println(collect);

anyMatch:用来判断匹配条件 返回boolean类型

List<Author> authors = getAuthors();
boolean b = authors.stream()
.anyMatch(author -> author.getAge() > 29); //判断是否有年龄大于29的 System.out.println(true);

allMatch:用来判断所有条件是否都匹配 返回boolean类型

List<Author> authors = getAuthors();
boolean b = authors.stream()
.allMatch(author -> author.getAge() >= 18); //判断是否是所有人的年龄都大于18 System.out.println(b);

noneMatch:用来判断所有条件是否都不匹配 返回boolean类型

List<Author> authors = getAuthors();
boolean b = authors.stream()
.noneMatch(author -> author.getAge() > 100); System.out.println(b);

findAny:获取流中的任意元素

List<Author> authors = getAuthors();
Optional<Author> any = authors.stream()
.findAny(); //随机的 System.out.println(any);

findFirst:获取流中的第一个元素

List<Author> authors = getAuthors();
Optional<Author> first = authors.stream()
.sorted((o1,o2) -> o1.getAge() - o2.getAge())
.findFirst(); first.ifPresent(author -> System.out.println(author.getName()));

reduce:把流中的数据按照指定的方式计算出一个结果

List<Author> authors = getAuthors();
//求年龄总和
Integer reduce = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(0, (result, element) -> result + element);
System.out.println(reduce); //求所有年龄最大的值
Integer max = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);//result为Integer.MIN_VALUE,后面计算比较继续赋值给result
System.out.println(max); //求所有年龄最小的值, reduce中两个参数第一个作为初始值
Integer min = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result); //result为Integer.MAX_VALUE,后面计算比较继续赋值给result
System.out.println(min); //求最小值年龄,reduce一个参数默认将列表第一个值 赋值给result作为初始值比较
Optional<Integer> minOne = authors.stream()
.distinct()
.map(author -> author.getAge())
.reduce((result, element) -> result > element ? element : result);
System.out.println(minOne.get());

需要准备的静态数据

    //使用数据
private static List<Author> getAuthors(){
//数据初始化
Author author = 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 , "吹或不吹", "爱情,个人传记",56,"一个哲学家的恋爱观注定很难把他所在的时代理解")); books3.add(new Book(5L, "你的剑就是我的剑", "爱情" ,56,"无法想象一个武者能对他的伴侣这么的宽容"));
books3.add(new Book(6L, "风与剑","个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
books3.add(new Book(6L,"风与剑","个人传记",100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?")); author.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3); List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
return authorList;
}

需要准备的实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Book { //id
private long id;
//姓名
private String name;
//年龄
private String category;
//评分
private int score;
//简介
private String intro;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class Author implements Comparable<Author> { //id
private Long id;
//姓名
private String name ;
//年龄
private Integer age;
//简介
private String intro;
//作品
private List<Book> books ; //比较排序
@Override
public int compareTo(Author o) {
return o.getAge() - this.getAge();
}
}

Stream流使用的更多相关文章

  1. Atiti 重定向标准输出到字符串转接口adapter stream流体系 以及 重定向到字符串

    Atiti 重定向标准输出到字符串转接口adapter stream流体系 以及 重定向到字符串 原理::syso  向ByteArrayOutputStream这个流理想write字节..然后可以使 ...

  2. 在stream流和byte[]中查找(搜索)指定字符串

    在 stream流 和 byte[] 中查找(搜索)指定字符串 这里注重看的是两个 Search 的扩展方法,一个是 stream 类型的扩展,另一个是 byte[] 类型的扩展, 如果大家有更好的“ ...

  3. 这可能是史上最好的 Java8 新特性 Stream 流教程

    本文翻译自 https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ 作者: @Winterbe 欢迎关注个人微信公众 ...

  4. (六)jdk8学习心得之Stream流

    六.Stream流 1. 什么是stream流 现阶段,可以把stream流看成一个高级版的Iterator.普通的Iterator只能实现遍历,遍历做什么,就需要具体些功能代码函数了.而这个stre ...

  5. stream流操作List工具类

    工作中操作List对于程序猿来说是"基本操作",为了更加便利,对JDK8的新特性stream流进行二次封装.话不多说,直接上代码 package com.mydemo; impor ...

  6. java8 Stream的实现原理 (从零开始实现一个stream流)

    1.Stream 流的介绍 1.1 java8 stream介绍 java8新增了stream流的特性,能够让用户以函数式的方式.更为简单的操纵集合等数据结构,并实现了用户无感知的并行计算. 1.2  ...

  7. NodeJS Stream流

    NodeJS Stream流 流数据在网络通信中至关重要,nodeJS用Stream提供了一个抽象接口,node中有很多对象实现了这个接口,提供统一的操作体验 基本流类型 NodeJS中,Stream ...

  8. 关于Java8 Stream流的利与弊 Java初学者,大神勿喷

    题目需求: 1:第一个队伍只要名字为3个字成员的姓名,存储到新集合 2:第一个队伍筛选之后只要前3人:存储到一个新集合 3:第2个队伍只要姓张的成员姓名:存储到一个新集合 4:第2个队伍不要前2人,存 ...

  9. 13函数式编程&Stream流

    13.1常用的函数式接口总结   接口名称 方法名称 抽象/默认  延迟/终结 方法描述 Supplier get 抽象 终结 供给型接口,无参有返回值,主要用于 Consumer accept 抽象 ...

  10. Java8的Stream流(一) --- 基础用法

    Java8中的Stream Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象. Stream的特性及优点: 无存储. Stream不是一种数据 ...

随机推荐

  1. ping: sina.cn: Name or service not known

    该方法针对Ubuntu18及以后版本. 第一次遇到ping:报错Name or service not known这个问题在百度上找了很久说的都是什么修改 /etc/resolv.conf,但每次修改 ...

  2. 理解 Spring IoC 容器

    控制反转与大家熟知的依赖注入同理, 这是通过依赖注入对象的过程. 创建 Bean 后, 依赖的对象由控制反转容器通过构造参数 工厂方法参数或者属性注入. 创建过程相对于普通创建对象的过程是反向, 称之 ...

  3. Vite+React搭建开发构建环境实践

    前言 使用 Vite 已经有两年了,期间使用它开发过单页面应用,也开发过浏览器扩展插件,对比日常工作中用到的 webpack 构建速度大幅提升,开发体验也好很多. 虽然相比于 webpack 来说简单 ...

  4. 【学习笔记】前馈神经网络(ANN)

    前言 最近跟着<神经网络与深度学习>把机器学习的内容简单回顾了一遍,并进行了一定的查缺补漏,比如SVM的一些理解,one-hot向量,softmax回归等等. 然后我将继续跟着这本书,开始 ...

  5. linux软链接的创建、修改和删除

    创建 ln -s [源文件或目录] [目标文件或目录] 修改 ln –snf [新的源文件或目录] [目标文件或目录] 删除 rm –rf 软链接名称 注意,上面这种形式可能会让人产生担忧,害怕删除的 ...

  6. 如何调试 Docker

    开启 Debug 模式 在 dockerd 配置文件 daemon.json(默认位于 /etc/docker/)中添加 { "debug": true } 重启守护进程. $ s ...

  7. 在CentOS 8服务器上搭建FastDFS环境

    什么是FastDFS? 这里,我就摘录下百度百科上对于FastDFS的描述. FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储.文件同步.文件访问(文件上传.文件下 ...

  8. css语言

    css:样式表.级联样式表.层叠样式表 css写在style标签里面,放在head标签中:大括号中写键值对语法 color:文字颜色 Font-family:字体 Font-size:字号 text- ...

  9. PAT (Basic Level) Practice 1012 数字分类 分数 20

    给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字: A1​ = 能被 5 整除的数字中所有偶数的和: A2​ = 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n1​−n ...

  10. Java 读写锁 ReadWriteLock 原理与应用场景详解

    Java并发编程提供了读写锁,主要用于读多写少的场景,今天我就重点来讲解读写锁的底层实现原理@mikechen 什么是读写锁? 读写锁并不是JAVA所特有的读写锁(Readers-Writer Loc ...