文章目录

一、Stream流(工厂的流水线)

1、Stream流的介绍

2、Stream步骤

二、创建Stream流

三、中间操作

1、筛选与切片

2、映射

3、排序

4、查找与匹配

5、归约与收集


一、Stream流(工厂的流水线)

1、Stream流的介绍

Stream是 Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。

Stream是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。“集合讲的是数据,流讲的是计算!”

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

2、Stream步骤:

  1. 创建Stream 通过数据源(集合、数组)创建Stream流
  2. 调用Stream的中间方法,处理数据
  3. 调用Stream的终结方法,接收处理后的数据

二、创建Stream流

第一种方式:通过Collection系列集合提供的Stream() 或 parallelStream()

public class StreamAPI01 {@Testpublic void test(){//1.通过Collection系列集合提供的Stream() 或 parallelStream()List<String> list = new ArrayList<>();Stream<String> stream01 = list.stream();}
}

第二种方式:通过Arrays 中的静态方法 stream() 获取数组流

public class StreamAPI01 {@Testpublic void test(){//2.通过Arrays 中的静态方法 stream() 获取数组流Employee[] emps = new Employee[10];Stream<Employee> stream02 = Arrays.stream(emps);}
}

第三种方式:通过Stream类中的静态方法 of()

public class StreamAPI01 {@Testpublic void test(){//3.通过Stream类中的静态方法 of()Stream<String> stream03 = Stream.of("aa", "bb", "cc");}
}

第四种方式:创建无限流

public class StreamAPI01 {@Testpublic void test(){//4.创建无限流//迭代Stream<Integer> stream04 = Stream.iterate(0,(x)->x+2);stream04.limit(10).forEach(System.out::println);//生成Stream.generate(()-> Math.random()).limit(5).forEach(System.out::println);}
}

三、中间操作

0、准备操作-创建 Employee类

public class Employee {private String name;private Integer age;private Double salary;public Employee() {}public Employee(String name, int age, double salary) {this.name = name;this.age = age;this.salary = salary;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(int age) {this.age = age;}public Double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Employee employee = (Employee) o;return Objects.equals(name, employee.name) && Objects.equals(age, employee.age) && Objects.equals(salary, employee.salary);}@Overridepublic int hashCode() {return Objects.hash(name, age, salary);}@Overridepublic String toString() {return "Employee{" +"name='" + name + '\'' +", age=" + age +", salary=" + salary +'}';}
}

1、筛选与切片

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

filter 接收Lambda ,从流中排除某些元素。

public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));/*** filter 接收Lambda ,从流中排除某些元素。*/@Testpublic void test01() {//中间操作:过滤出年龄大于32的员工Stream<Employee> stream = employees.stream().filter((e) -> {return e.getAge() > 32;});//终止操作:一次执行全部内容,即"惰性求值"List<Employee> collect = stream.collect(Collectors.toList()); //接收过滤后的最终结果collect.forEach(System.out::println);}
}
limit 截断流,使其元素不超过给定数量。(短路操作)
public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test02() {//中间操作:获取工资大于5000的前三位员工Stream<Employee> stream = employees.stream().filter((e) -> {return e.getSalary() > 5000;}).limit(3);//终止操作List<Employee> collect = stream.collect(Collectors.toList());collect.forEach(System.out::println);}
}

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

public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test03() {//中间操作:跳过前两个符合条件的数据Stream<Employee> stream = employees.stream().filter((e) -> {return e.getSalary() > 5000;}).skip(2);//终止操作List<Employee> collect = stream.collect(Collectors.toList());collect.forEach(System.out::println);}
}

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

public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test04() {//中间操作:跳过前两个符合条件的数据Stream<Employee> stream = employees.stream().filter((e) -> {return e.getSalary() > 5000;}).distinct();//终止操作List<Employee> collect = stream.collect(Collectors.toList());collect.forEach(System.out::println);}
}

2、映射

map 接收Lambda ,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被分发到每个元素上,并将其映射成一个新的元素。
flatMap 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
map 接收Lambda ,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被分发到每个元素上,并将其映射成一个新的元素。
public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test1(){Stream<String> str = employees.stream().map((e) -> e.getName());System.out.println("-------------------------------------------");//map() 将函数应用到每一个元素上//将每一个字符串变成大写字符串List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");Stream<String> stream = strList.stream().map(String::toUpperCase);stream.forEach(System.out::println);//将每一个字符串元素,拆成字符输出Stream<Stream<Character>> stream2 = strList.stream().map(StreamAPI03::filterCharacter);stream2.forEach((sm) -> {sm.forEach(System.out::println);});}//接收一个字符串,将其转成字符,并添加到list集合中,最后转成流返回public static Stream<Character> filterCharacter(String str){List<Character> list = new ArrayList<>();for (Character ch : str.toCharArray()) {list.add(ch);}return list.stream();}
}
flatMap 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test2(){//flatMap 合并流List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");Stream<Character> stream3 = strList.stream().flatMap(StreamAPI03::filterCharacter);stream3.forEach(System.out::println);}//接收一个字符串,将其转成字符,并添加到list集合中,最后转成流返回public static Stream<Character> filterCharacter(String str){List<Character> list = new ArrayList<>();for (Character ch : str.toCharArray()) {list.add(ch);}return list.stream();}}

3、排序

sorted() 自然排序
sorted(Comparator com) 定制排序

sorted() 自然排序

public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test1(){List<String> list = Arrays.asList("dd", "ss", "aa","ab","bb","cd");//排序list.stream().sorted().forEach(System.out::println);}
}
sorted(Comparator com) 定制排序
public class StreamAPI02 {List<Employee> employees = Arrays.asList(new Employee("张三", 18, 9999.99),new Employee("李四", 58, 5555.55),new Employee("王五", 26, 3333.33),new Employee("赵六", 36, 6666.66),new Employee("田七", 12, 8888.88),new Employee("田七", 12, 8888.88));@Testpublic void test2(){//升序,先按年龄排序,年龄相等按名字排序employees.stream().sorted((e1,e2)->{if (e1.getAge().equals(e2.getAge())){return e1.getName().compareTo(e2.getName());}else{return -e1.getAge().compareTo(e2.getAge());}}).forEach(System.out::println);}
}

4、查找与匹配

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

创建新的员工类

public class Employee02 {private int id;private String name;private int age;private double salary;private Status status;public Employee02() {}public Employee02(int id, String name, int age, double salary, Status status) {this.id = id;this.name = name;this.age = age;this.salary = salary;this.status = status;}public Status getStatus() {return status;}public void setStatus(Status status) {this.status = status;}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 getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public String show() {return "测试方法引用!";}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Employee02 that = (Employee02) o;return id == that.id && age == that.age && Double.compare(that.salary, salary) == 0 && Objects.equals(name, that.name) && status == that.status;}@Overridepublic int hashCode() {return Objects.hash(id, name, age, salary, status);}@Overridepublic String toString() {return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status+ "]";}public enum Status {FREE, BUSY, VOCATION;}
}

allMatch——检查是否匹配所有元素
anyMatch——检查是否至少匹配一个元素
noneMatch——检查是否没有匹配的元素

public class StreamAPI05 {List<Employee02> emps = Arrays.asList(new Employee02(102, "李四", 59, 6666.66, Status.BUSY),new Employee02(101, "张三", 18, 9999.99, Status.FREE),new Employee02(103, "王五", 28, 3333.33, Status.VOCATION),new Employee02(104, "赵六", 8, 7777.77, Status.BUSY),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(105, "田七", 38, 5555.55, Status.BUSY));@Testpublic void test1(){//Status.BUSY 是否匹配全部元素boolean bl = emps.stream().allMatch((e) -> e.getStatus().equals(Status.BUSY));System.out.println(bl);//anyMatch() 是否匹配任意一个元素boolean bl1 = emps.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY));System.out.println(bl1);//anyMatch 检查有没有匹配的元素boolean bl2 = emps.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY));System.out.println(bl2);}
}

findFirst——返回第一个元素
findAny——返回当前流中的任意元素

public class StreamAPI05 {List<Employee02> emps = Arrays.asList(new Employee02(102, "李四", 59, 6666.66, Status.BUSY),new Employee02(101, "张三", 18, 9999.99, Status.FREE),new Employee02(103, "王五", 28, 3333.33, Status.VOCATION),new Employee02(104, "赵六", 8, 7777.77, Status.BUSY),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(105, "田七", 38, 5555.55, Status.BUSY));@Testpublic void test2(){//返回排序后的第一个元素Optional<Employee02> op = emps.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst();System.out.println(op.get());System.out.println("--------------------------------");//返回当前流中 等于Status.FREE 的任意元素Optional<Employee02> op2 = emps.parallelStream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();System.out.println(op2.get());}
}

count——返回流中元素的总个数
max——返回流中最大值
min——返回流中最小值

public class StreamAPI05 {List<Employee02> emps = Arrays.asList(new Employee02(102, "李四", 59, 6666.66, Status.BUSY),new Employee02(101, "张三", 18, 9999.99, Status.FREE),new Employee02(103, "王五", 28, 3333.33, Status.VOCATION),new Employee02(104, "赵六", 8, 7777.77, Status.BUSY),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(105, "田七", 38, 5555.55, Status.BUSY));@Testpublic void test3(){//返回元素等于Status.FREE,的总个数long count = emps.stream().filter((e) -> e.getStatus().equals(Status.FREE)).count();System.out.println(count);//返回当前流的最大值Optional<Double> op = emps.stream().map(Employee02::getSalary).max(Double::compare);System.out.println(op.get());//返回当前流的最小值Optional<Employee02> op2 = emps.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));System.out.println(op2.get());}
}

5、归约与收集

reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法

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

public class StreamAPI05 {List<Employee02> emps = Arrays.asList(new Employee02(102, "李四", 59, 6666.66, Status.BUSY),new Employee02(101, "张三", 18, 9999.99, Status.FREE),new Employee02(103, "王五", 28, 3333.33, Status.VOCATION),new Employee02(104, "赵六", 8, 7777.77, Status.BUSY),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(105, "田七", 38, 5555.55, Status.BUSY));public void test1(){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);System.out.println("----------------------------------------");//计算工资的总和Optional<Double> op = emps.stream().map(Employee02::getSalary).reduce(Double::sum);System.out.println(op.get());}
}

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

public class StreamAPI05 {List<Employee02> emps = Arrays.asList(new Employee02(102, "李四", 59, 6666.66, Status.BUSY),new Employee02(101, "张三", 18, 9999.99, Status.FREE),new Employee02(103, "王五", 28, 3333.33, Status.VOCATION),new Employee02(104, "赵六", 8, 7777.77, Status.BUSY),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(104, "赵六", 8, 7777.77, Status.FREE),new Employee02(105, "田七", 38, 5555.55, Status.BUSY));@Testpublic void test2(){//获取emps集合中的全部名字,并存到List中List<String> list = emps.stream().map(Employee02::getName).collect(Collectors.toList());list.forEach(System.out::println);System.out.println("----------------------------------");//获取emps集合中的全部名字,并存到Set中Set<String> set = emps.stream().map(Employee02::getName).collect(Collectors.toSet());set.forEach(System.out::println);System.out.println("----------------------------------");//获取emps集合中的全部名字,并存到HashSet中HashSet<String> hs = emps.stream().map(Employee02::getName).collect(Collectors.toCollection(HashSet::new));hs.forEach(System.out::println);}
}

Stream流(工厂的流水线)相关推荐

  1. 函数式接口和Stream流式思想

    函数式接口和Stream 1. 函数式接口 1.1 函数式接口概述 利用接口操作语法格式,对于方法的声明作出二次封装!!!方法声明:权限修饰符 是否静态 返回值类型 方法名(形式参数列表);对于接口而 ...

  2. stream distinct去重_再来看看Java的新特性——Stream流

    半年前开始试着使用Java的新特性,给我印象最深的就是Stream流和Optional.其中Stream提高了看法效率,让代码看起来十分清爽. 为什么要使用流? 摘要中已经说明了,为了提高开发效率.流 ...

  3. java day24【Stream流、方法引用】

    第一章 Stream流 说到Stream便容易想到I/O Stream,而实际上,谁规定"流"就一定是"IO流"呢?在Java 8中,得益于Lambda所带来的 ...

  4. 2021最新 JDK17 之 JAVA基础 Stream 流

    目录 1.什么是Stream 2.流的构成与转换 3.流的操作 4.并行处理 5.Collector 1.什么是Stream Java 8之前的集合类库主要依赖于 外部迭代(external iter ...

  5. 定时器、Lambda表达式、Stream流

    一.定时器 * 定时器Timer类:在java.util包下!线程调度任务以供将来在后台线程中执行的功能. 任务可以安排一次执行,或者定期重复执行.* 构造方法:Timer() 创建一个新的计时器.* ...

  6. JDK8新特性:Lambda表达式、Stream流、日期时间工具类

    重要特性: 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值. 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号. 可选的大括号:如果主体包含了一个语句,就不需要大括号. ...

  7. JDK8新特性(三):集合之 Stream 流式操作

    1.Stream流由来 首先我们应该知道:Stream流的出现,主要是用在集合的操作上.在我们日常的工作中,经常需要对集合中的元素进行相关操作.诸如:增加.删除.获取元素.遍历. 最典型的就是集合遍历 ...

  8. Java8 方法引用和Stream流

    Stream 流API 什么是流 流的操作种类 流的操作过程 使用流 创建流 集合 数组 值 筛选 filter 去重 distinct 截取 limit 跳过 skip 映射 map 合并多个流 是 ...

  9. 带你看看JDK8新特性:Stream流

    相信兄弟萌在学习时碰到过这样的代码吧: List<String> list = new ArrayList(); list.stream().forEach(a-> System.o ...

最新文章

  1. 解决SSH连接出现 Software caused connection abort 的问题
  2. Linux终端中设置vi编辑命令
  3. selenium - 下拉框操作
  4. python_day02 上节课知识点回顾
  5. JavaScript:向数组开头添加
  6. 宣布 Azure Backup 支持备份 Windows Server 2008
  7. 第四章 PX4-Pixhawk-MPU6000传感器驱动解析
  8. 在集设把优秀的设计合集,轻松追寻设计灵感
  9. 顶级产品经理是如何写产品需求文档(PRD)的
  10. static全局变量与普通的全局变量有什么区别?static局部变量和普通局部变量有什么区别?static函数与普通函数有什么区别?...
  11. 《IT项目管理那些事儿》——国内第一本项目管理的实践书籍
  12. [转载] 比较器(Comparable和Comparator)、自然排序、定制排序
  13. 当vue遇到pwa--vue+pwa移动端适配解决方案模板案例
  14. flink源码分析_源码解析 | 万字长文详解 Flink 中的 CopyOnWriteStateTable
  15. WindwosServer系统一些设置【网卡驱动修复】【安装UWP应用】【服务器管理取消开机自启动】
  16. 国内拉取 gcr.io 镜像(Google Kubernetes 镜像)
  17. iOS 防止录屏和截屏的监听
  18. Cairo 图形指南 (5) —— 形状与填充
  19. 董卫凤:不服输的华丽转身(二)
  20. 算法竞赛---day1(等差素数列)

热门文章

  1. 使用DALI模块加速
  2. Ubuntu 16.04 开机运行程序或脚本
  3. 反射、注解、动态代理、JDK8新特性
  4. 研究生两年时间发表论文11篇
  5. (模块化)Finding and evaluating community structure in net work
  6. 三星 摄像头 linux,基于Linux 3.0.8 Samsung FIMC(S5PV210) 的摄像头驱动框架解读(一)...
  7. GTX1080 matlab计算,GTX 1080显卡计算性能测试:专业的归专业,游戏的归游戏
  8. 人工智能智能语音交互技术与应用
  9. 计算机自动配置的ip地址,电脑自动获取IP地址的设置方法(图文)
  10. 图解文玩核桃的种类和特点