1.简述

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一 个就是 Stream API。

Stream 是处理集合的抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询,比如可以实现group by的分组操作。总之就是Stream API提供的高效简介的数据处理方式。

流(Stream)是什么?心脏的血液通过血管流变全身,在血管中的时候就可以看做流,生病了需要通过血管进行输液,也就是说在这个流中进行了操作。心脏的血液可以看做一个数据集合,转换成流通过血管进行输送,输液这个操作就相当于是我们Stream API 所做的操作,也就是对这个流进行计算处理。

集合是数据,流是计算。

需要注意的是:

  1.Stream 自己不会存储元素。

  2.Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。

  3.Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream三步走:

  1.创建流

  2.操作流

  3.终止操作获取结果,注意:流进行了终止操作后,不能再次使用

2.API操作案例

  2.1.创建流

        //集合创建流Stream<Student> stream1 = studentList.stream();//Stream静态方法创建流Stream<Student> stream2 = Stream.of(new Student(1, "张三", 12, 69),new Student(2, "李四", 12, 78.5),new Student(3, "王五", 13, 95),new Student(4, "赵六", 14, 23),new Student(5, "孙七", 11, 55.5));//数组创建流Stream<Student> stream = Arrays.stream(new Student[]{});

  2.2.操作流

    2.2.1 筛选和分割

      filter(Predicate p) 接收 Lambda , 从流中排除某些元素。

      distinct() 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素,切记重写

      limit(long maxSize) 截断流,使其元素不超过给定数量。limit取值找到符合条件的就结束了 不会继续查找所有

      skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补

        //filter过滤年龄大于12的
        studentList.stream().filter(student -> student.getAge() > 12).forEach(System.out::println);System.out.println("--------------");//distinct去重
        studentList.stream().distinct().forEach(System.out::println);System.out.println("--------------");//过滤之后取前2,有点类似mysql的limit了,// limit取值找到符合条件的就结束了 不会继续查找所有,下面的输出语句只会执行2次,因为前面两个就是满足条件的
        studentList.stream().filter((student) -> {System.out.println("执行过滤");return student.getAge() >= 12;}).limit(2).forEach(System.out::println);System.out.println("--------------");//skip跳过满足条件前两个
        studentList.stream().filter(student ->  student.getAge() >= 12).skip(2).forEach(System.out::println);

    2.2.2 映射

      map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素

      flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

      有点类似list的 add方法和addAll,一个添加单个元素到集合中,一个是将集合中元素逐一添加到另一个集合中

    public void testStream2() {//将map中的函数应用到每个元素上,生成一个新的元素,也就是收集每个student的名字组成一个新的元素
        studentList.stream().distinct().map(student -> student.getName()).forEach(System.out::println);System.out.println("--------");//调用creatStream方法将每个Student对象都转换成一个流,然后flatMap将每个流汇总成一个流
        studentList.stream().distinct().flatMap(StreamTest::creatStream).forEach(System.out::println);}public static Stream<Student> creatStream(Student student){return Stream.of(student);}

    2.2.3 排序

      sorted() 产生一个新流,其中按自然顺序排序

      sorted(Comparator comp) 产生一个新流,其中按比较器顺序排序

  2.3 流结果获取

    2.3.1查找与匹配 

      allMatch(Predicate p) 检查是否匹配所有元素

      anyMatch(Predicate p) 检查是否至少匹配一个元素

      noneMatch(Predicate p) 检查是否没有匹配所有元素

      findFirst() 从流的操作中返回第一个元素(封装在Optional中)

      findAny() 返回当前流中的任意元素(封装在Optional中),并行流结果有随机性

      count() 返回流中元素总数

      max(Comparator c) 返回流中最大值 (封装在Optional中)

      min(Comparator c) 返回流中最小值 (封装在Optional中)

      forEach(Consumer c) 内部迭代

     //allMatch(Predicate p) 检查是否匹配所有元素 是否所有student age > 12boolean result = studentList.stream().allMatch(student -> student.getAge() > 12);System.out.println(result);//anyMatch(Predicate p) 检查是否至少匹配一个元素result = studentList.stream().anyMatch(student -> student.getAge() == 12);System.out.println(result);//noneMatch(Predicate p) 检查是否没有匹配所有元素result = studentList.stream().noneMatch(student -> student.getAge() < 11);System.out.println(result);//findFirst() 从流的操作中返回第一个元素(封装在Optional中)//按score升序 之后取第一个Student student = studentList.stream().sorted((student1, student2) -> Double.compare(student1.getScore(), student2.getScore())).findFirst().get();System.out.println(student);student = studentList.stream().findAny().get();System.out.println(student);

    2.3.2 归约

      reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 T

      reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>

      map 和 reduce 的连接通常称为 map-reduce 模式

        //累加,将流中元素进行求和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);//求student的总分Double allScore = studentList.stream().map(student -> student.getScore()).reduce(Double::sum).get();System.out.println(allScore);

    2.3.3 收集     

      collect(Collector c) 将流转换为其他形式。接收一个 Collector接口(收集器)的实现,用于给Stream中元素做汇总的方法

      Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。

      1.8提供了Collectors 工具类可以方便地创建常见收集器实例

Collectors:

        List<Student> studentList = Arrays.asList(new Student(1, "张三", 12, 69, Student.Clazz.Clazz2),new Student(2, "李四", 12, 78.5,Student.Clazz.Clazz2),new Student(3, "王五", 13, 95, Student.Clazz.Clazz3),new Student(4, "赵六", 14, 23, Student.Clazz.Clazz3),new Student(5, "孙七", 11, 55.5, Student.Clazz.Clazz1),new Student(5, "孙七", 11, 55.5, Student.Clazz.Clazz1));//toList() 收集到List集合中List<String> nameList = studentList.stream().map(student -> student.getName()).collect(Collectors.toList());System.out.println(nameList);//toSet() 收集到Set集合中 自动去重 默认返回的HashSetSet<String> nameSet= studentList.stream().map(student -> student.getName()).collect(Collectors.toSet());System.out.println(nameSet);System.out.println(nameSet.getClass());//返回指定集合类型TreeSet<String> nameTreeSet= studentList.stream().map(student -> student.getName()).collect(Collectors.toCollection(TreeSet::new));System.out.println(nameTreeSet.getClass());//分组groupingBy 返回map集合 类似sql group by了//根据年级分组Map<Student.Clazz, List<Student>> map = studentList.stream().collect(Collectors.groupingBy(Student::getClazz));System.out.println(map);//多次分组//先按年级再按年龄Map<Student.Clazz, Map<Integer, List<Student>>> map2 = studentList.stream().collect(Collectors.groupingBy(Student::getClazz, Collectors.groupingBy(Student::getAge)));System.out.println(map2);//分区partitioningBy 入参是个断言型接口
        studentList.stream().collect(Collectors.partitioningBy((student) -> student.getScore() >= 60));//summarizingDouble 对某个值进行 数据统计输出//对score进行统计DoubleSummaryStatistics statistics = studentList.stream().collect(Collectors.summarizingDouble(Student::getScore));statistics.getAverage();statistics.getCount();statistics.getMax();statistics.getMin();statistics.getSum();

Student类:

    private int id;private String name;private int age;private double score;private Clazz clazz;public Student(String name) {this.name = name;}public Student(int id, String name, int age, double score) {this.id = id;this.name = name;this.age = age;this.score = score;}public Student(int id, String name, int age, double score, Clazz clazz) {this.id = id;this.name = name;this.age = age;this.score = score;this.clazz = clazz;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getScore() {return score;}public void setScore(double score) {this.score = score;}public Clazz getClazz() {return clazz;}public void setClazz(Clazz clazz) {this.clazz = clazz;}public String show() {return "测试方法引用";}@Overridepublic int hashCode() {final int prime = 11;int hashCode = 1;hashCode = prime * hashCode + age;hashCode = prime * hashCode + id;hashCode = prime * hashCode + ((name == null) ? 0 : name.hashCode());long temp;temp = Double.doubleToLongBits(score);hashCode = prime * hashCode + (int) (temp ^ (temp >>> 32));return hashCode;}@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (obj == null) {return false;}if (getClass() != obj.getClass()) {return false;}Student other = (Student) obj;if (age != other.age) {return false;}if (id != other.id) {return false;}if (name == null) {if (other.name != null) {return false;}} else if (!name.equals(other.name)) {return false;}if (Double.doubleToLongBits(score) != Double.doubleToLongBits(other.score)) {return false;}return true;}@Overridepublic String toString() {return "[id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + ", Class=" + clazz + "]";}public static enum Clazz{Clazz1,Clazz2,Clazz3,}

转载于:https://www.cnblogs.com/nijunyang/p/11334814.html

java8(2)--- Stream API相关推荐

  1. java8(三)Stream API

    文章目录 Stream API Stream和Collection的区别 Stream操作的三个步骤 创建Stream 方法一:通过集合创建 方法二:通过数组创建 通过Stream类的静态方法 of创 ...

  2. Java8(八)——Stream的collector操作

    前言 本篇博客对应<Java8 in action>一书的第六章,主要总结收集器的操作,在第六章的开头,这本中用一个简单的例子介绍了使用收集器的便捷.这里还是先总结一下这个实例.在原书实例 ...

  3. 【java8新特性】——Stream API详解(二)

    一.简介 java8新添加了一个特性:流Stream.Stream让开发者能够以一种声明的方式处理数据源(集合.数组等),它专注于对数据源进行各种高效的聚合操作(aggregate operation ...

  4. Java8初体验(二)Stream语法详解(转)

    本文转自http://ifeve.com/stream/ Java8初体验(二)Stream语法详解 感谢同事[天锦]的投稿.投稿请联系 tengfei@ifeve.com 上篇文章Java8初体验( ...

  5. java8新特性(4)— Stream流

    java8新特性(4)- Stream流 遍历集合更强大 package com.common.jdk8;import java.util.*; import java.util.stream.Col ...

  6. Hadoop入门(三)HDFS API

    一..HDFS 常用类 Configuration  配置 Path  路径 FileSystem  文件系统 Stream  流 IOUtils  IO工具 API文档 二.类解析 (1)Confi ...

  7. 函数式编程(JAVA)——Stream流

    函数式编程(JAVA)--Stream流 概述 Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作.可以更方便的让我们对集合或数组操作. 下述 ...

  8. Flink学习笔记(十一)Table API 和 SQL

    文章目录 11. Table API 和 SQL 11.1 快速上手 11.1.1 需要依赖 11.1.2 示例 11.2 基本 API 11.2.1 程序架构 11.2.2 创建表环境 11.2.3 ...

  9. Java中的微信支付(2):API V3 微信平台证书的获取与刷新

    1. 前言 在Java 中的微信支付(1):API V3 版本签名详解一文中胖哥讲解了微信支付 V3 版本 API 的签名,当我方(你自己的服务器)请求微信支付服务器时需要根据我方的API 证书对参数 ...

最新文章

  1. Stack Overflow 上人气爆表的10个 Java 问题
  2. oracle 数据 导出 excel 自动分多个文件,从oracle数据库中导出大量数据到excel中为什么自动分成了好几个excel文件《excel表格新手入门》...
  3. linux 邮件日志,linux下如何建立邮件日志
  4. (转)Hibernate事务管理
  5. 第十三节:使用Lombok简化你的代码
  6. php下载隐藏,php – 隐藏下载URL
  7. Linux内核源码目录
  8. Android学习路线指南-------任玉刚
  9. linux u盘读取速度,[操作系统]linux dd命令测试U盘读写速度
  10. 第一届程序设计竞赛题解(G题)
  11. 细胞制备流程图_B细胞恶性肿瘤的CAR-T免疫治疗或可出现新进展
  12. Odoo16正式版于2022年9月12日发布
  13. eclipse启动慢解决方法
  14. [编辑器]KindEditor 是什么?
  15. vscode 一直显示Load project: XXXX,保存时提示“从 “‘Vetur‘, ‘Vue Language Features (Volar)‘“ (configure)中获取代码操作”
  16. 10.IDEAD 的xml中配置DTD
  17. “十月围城”中国高校SAS数据分析大赛将再燃战火
  18. 软件-DiskSpeekUp:DiskSpeekUp(磁盘整理工具)
  19. WINDOWS性能监控器的监视以及邮件预警配置
  20. python开发的著名网站_python开发著名网站_python开发的著名软件 - CSDN

热门文章

  1. android的动态注册,Android JNI 函数注册的两种方式(静态注册/动态注册)
  2. 计算机科学技术主业人才培养模式,计算机科学和技术专业人才培养模式改革和创新.doc...
  3. 分页的limit_Presto分页功能概述
  4. python 邮件中生成图表_60秒一口Python:147个demo,助你从新手小白步步进阶编程高手...
  5. js 线段上某点的坐标_测绘测量中常用的坐标系
  6. Ansible Inventory
  7. MongoDB Insert(插入)
  8. C语言 Win动态库
  9. python svm 实战_opencv-python 入门实战:传统方法Hog+svm实现目标检测
  10. html跳动爱心代码,html+css实现跳动爱心❥(^_-)-Go语言中文社区