[java高级]-Stream API说明
1、Stream API 说明
-
Java8 中有两大最为重要的改变。第一个是 Lambda 表达式;另外一个则 是 Stream API。
-
Stream API (java.util.stream) 把真正的函数式编程风格引入到 Java 中。这 是目前为止对 Java 类库最好的补充,因为 Stream API 可以极大提供 Java 程 序员的生产力,让程序员写出高效率、干净、简洁的代码。
-
Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进 行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。 使用 Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。 也可以使用 Stream API 来并行执行操作。简言之,Stream API 提供了一种 高效且易于使用的处理数据的方式。
2、为什么要使用 Stream API
-
实际开发中,项目中多数数据源都来自于 Mysql,Oracle 等。但现在数 据源可以更多了,有 MongDB,Radis 等,而这些 NoSQL 的数据就需要 Java 层面去处理。
-
Stream 和 Collection 集合的区别:Collection 是一种静态的内存数据 结构,而 Stream 是有关计算的。前者是主要面向内存,存储在内存中, 后者主要是面向 CPU,通过 CPU 实现计算。
3、什么是 Stream
Stream 到底是什么呢? 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。 “集合讲的是数据,Stream 讲的是计算!”
注意:
①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新 Stream。
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
4、Stream 的操作三个步骤
- 1- 创建 Stream
一个数据源(如:集合、数组),获取一个流
- 2- 中间操作
一个中间操作链,对数据源的数据进行处理
- 3- 终止操作 (终端操作)
一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
5、创建 Stream
创建 Stream 方式一:通过集合
Java8 中的 Collection 接口被扩展,提供了两个获取流 的方法:
- default Stream stream() : 返回一个顺序流
- default Stream parallelStream() : 返回一个并行流
** 创建 Stream 方式二:通过数组 **
Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:
- static Stream stream(T[] array): 返回一个流
重载形式,能够处理对应基本类型的数组:
- public static IntStream stream(int[] array)
- public static LongStream stream(long[] array)
- public static DoubleStream stream(double[] array)
创建 Stream 方式三:通过 Stream 的 of()
可以调用 Stream 类静态方法 of(), 通过显示值创建一个 流。它可以接收任意数量的参数。
- public static Stream of(T... values) : 返回一个流
创建 Stream 方式四:创建无限流
可以使用静态方法 Stream.iterate()和 Stream.generate(), 创建无限流。
- 迭代
public static Stream iterate(final T seed, final UnaryOperator f)
- 生成
public static Stream generate(Supplier s)
// 方式四:创建无限流
@Test public void test4() {
// 迭代 //
public static<T> Stream<T> iterate(final T seed, final
// UnaryOperator<T> f)
Stream<Integer> stream = Stream.iterate(0, x -> x + 2); stream.limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream<Double> stream1 = Stream.generate(Math::random); stream1.limit(10).forEach(System.out::println);
}
6、Stream 的中间操作
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止 操作,否则中间操作不会执行任何的处理!而在终止操作时一次性全 部处理,称为“惰性求值”。
6.1- 筛选与切片
方 法 描 述
方 法 | ** 描 述 ** |
---|---|
filter(Predicate p) | 接收 Lambda , 从流中排除些元素 |
distinct() | 筛选,通过流所生成元素的 hashCode()和 equals() 去除重复元素 |
limit(long maxSize) | 截断流,使其元素不超过给定数量 |
skip(long n) | 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一 个空流。与 limit(n) 互补 |
6.2- 映 射
** 方法 ** | 描述 |
---|---|
map(Function f) | 接收一个函数作为参数,该函数会被应用到每个元 素上,并将其映射成一个新的元素。 |
mapToDouble(ToDoubleFunction f) | 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 DoubleStream。 |
mapToInt(ToIntFunction f) | 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 IntStream。 |
mapToLong(ToLongFunction f) | 接收一个函数作为参数,该函数会被应用到每个元 素上,产生一个新的 LongStream。 |
flatMap(Function f) | 接收一个函数作为参数,将流中的每个值都换成另 一个流,然后把所有流连接成一个流 |
6.3- 排序
方法 | 描述 |
---|---|
sorted() | 产生一个新流,其中按自然顺序排序 |
sorted(Comparator com) | 产生一个新流,其中按比较器顺序排序 |
7、Stream 的终止操作
-
终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例 如:List、Integer,甚至是 void 。
-
流进行了终止操作后,不能再次使用。
7.1- 匹配与查找
方法 | 描述 |
---|---|
allMatch(Predicate p) | 检查是否匹配所有元素 |
anyMatch(Predicate p) | 检查是否至少匹配一个元素 |
noneMatch(Predicate p) | 检查是否没有匹配所有元素 |
findFirst() | 返回第一个元素 |
findAny() | 返回当前流中的任意元素 |
count() | 返回流中元素总数 |
max(Comparator c) | 返回流中最大值 |
min(Comparator c) | 返回流中最小值 |
forEach(Consumer c) | 内部迭代 (使用 Collection 接口需要用户去做迭代, 称为外部迭代。相反,Stream API 使用内部迭 代——它帮你把迭代做了) |
7.2- 归约
方法 | 描述 |
---|---|
reduce(T iden, BinaryOperator b) | 可以将流中元素反复结合起来,得到一 个值。返回 T |
reduce(BinaryOperator b) | 可以将流中元素反复结合起来,得到一 个值。返回 Optional |
备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。
7.3- 收集
方 法 | 描 述 |
---|---|
collect(Collector c) | 将流转换为其他形式。接收一个 Collector 接口的实现,用于给 Stream 中元素做汇总 的方法 |
Collector 接口中方法的实现决定了如何对流执行收集的操作 (如收集到 List、Set、 Map)。
另外, Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例, 具体方法与实例如下表:
方法 | 返回类型 | 作用 |
---|---|---|
toList | List | 把流中元素收集到 List |
List emps= list.stream().collect(Collectors.toList()); | ||
toSet | Set | 把流中元素收集到 Set |
Set emps= list.stream().collect(Collectors.toSet()); | ||
toCollection | Collection | 把流中元素收集到创建的集合 |
Collection emps =list.stream().collect(Collectors.toCollection(ArrayList::new)); | ||
counting | Long | 计算流中元素的个数 |
long count = list.stream().collect(Collectors.counting()); | ||
summingInt | Integer | 对流中元素的整数属性求和 |
int total=list.stream().collect(Collectors.summingInt(Employee::getSalary)); | ||
averagingInt | Double | 计算流中元素 Integer 属性的平均值 |
double avg = list.stream().collect(Collectors.averagingInt(Employee::getSalary)); | IntSummaryStatistics | 收集流中 Integer 属性的统计值。如:平 均值 |
summarizingInt | ||
int SummaryStatisticsiss= list.stream().collect(Collectors.summarizingInt(Employee::getSalary)); | ||
joining | String | 连接流中每个字符串 |
String str= list.stream().map(Employee::getName).collect(Collectors.joining()); | ||
maxBy | Optional | 根据比较器选择最大值 |
Optionalmax= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary))); | ||
minBy | Optional | 根据比较器选择最小值 |
Optional min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary))); | ||
reducing | 归约产生的类型 | 从一个作为累加器的初始值开始, 利用 BinaryOperator 与流中元素逐 个结合,从而归约成单个值 |
int total=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum)); | ||
collectingAndThen | 转换函数返回的类型 | 包裹另一个收集器,对其结果转 换函数 |
int how= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size)); | ||
groupingBy | Map<K, List> | 根据某属性值对流分组,属性为 K, 结果为 V |
Map<Emp.Status, List> map= list.stream().collect(Collectors.groupingBy(Employee::getStatus)); | ||
partitioningBy | Map<Boolean, List> | 根据 true 或 false 进行分区 |
Map<Boolean,List> vd = list.stream().collect(Collectors.partitioningBy(Employee::getManage)); |
8、代码学习示例
8.1、bean:
- Employee.java 实例
package com.atguigu.java2;
/**
-
@author shkstart 邮箱:shkstart@126.com
*/
public class Employee {
private int id;
private String name;
private int age;
private double salary;
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 Employee() {
System.out.println("Employee().....");
}
public Employee(int id) {
this.id = id;
System.out.println("Employee(int id).....");
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee(int id, String name, int age, double salary) {
<span class="hljs-built_in">this</span>.id = id;
<span class="hljs-built_in">this</span>.name = name;
<span class="hljs-built_in">this</span>.age = age;
<span class="hljs-built_in">this</span>.salary = salary;
}
@Override
public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + ''' + ", age=" + age + ", salary=" + salary + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass()!= o.getClass())
return false;
<span class="hljs-type">Employee</span> <span class="hljs-variable">employee</span> <span class="hljs-operator">=</span> (Employee) o;
<span class="hljs-keyword">if</span> (id != employee.id)
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
<span class="hljs-keyword">if</span> (age != employee.age)
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
<span class="hljs-keyword">if</span> (Double.compare(employee.salary, salary) != <span class="hljs-number">0</span>)
<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
<span class="hljs-keyword">return</span> name != <span class="hljs-literal">null</span> ? name.equals(employee.name) : employee.name == <span class="hljs-literal">null</span>;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
temp = Double.doubleToLongBits(salary);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
- EmployeeData.java 调用实例的方法
package com.atguigu.java2;
import java.util.ArrayList;
import java.util.List;
/**
- 提供用于测试的数据
- @author shkstart 邮箱:shkstart@126.com
*/
public class EmployeeData {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List<Employee> <span class="hljs-title function_">getEmployees</span><span class="hljs-params">()</span>{
List<Employee> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1001</span>, <span class="hljs-string">"马化腾"</span>, <span class="hljs-number">34</span>, <span class="hljs-number">6000.38</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1002</span>, <span class="hljs-string">"马云"</span>, <span class="hljs-number">12</span>, <span class="hljs-number">9876.12</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1003</span>, <span class="hljs-string">"刘强东"</span>, <span class="hljs-number">33</span>, <span class="hljs-number">3000.82</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1004</span>, <span class="hljs-string">"雷军"</span>, <span class="hljs-number">26</span>, <span class="hljs-number">7657.37</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1005</span>, <span class="hljs-string">"李彦宏"</span>, <span class="hljs-number">65</span>, <span class="hljs-number">5555.32</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1006</span>, <span class="hljs-string">"比尔盖茨"</span>, <span class="hljs-number">42</span>, <span class="hljs-number">9500.43</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1007</span>, <span class="hljs-string">"任正非"</span>, <span class="hljs-number">26</span>, <span class="hljs-number">4333.32</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1008</span>, <span class="hljs-string">"扎克伯格"</span>, <span class="hljs-number">35</span>, <span class="hljs-number">2500.32</span>));
<span class="hljs-keyword">return</span> list;
}
}
8.2、创建 Stream 的四个方法
package com.atguigu.java3;
import com.atguigu.java2.Employee;
import com.atguigu.java2.EmployeeData;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
-
- Stream 关注的是对数据的运算,与 CPU 打交道
-
集合关注的是数据的存储,与内存打交道
-
-
①Stream 自己不会存储元素。
-
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新 Stream。
-
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
-
3.Stream 执行流程
-
① Stream 的实例化
-
② 一系列的中间操作(过滤、映射、...)
-
③ 终止操作
-
4. 说明:
-
4.1 一个中间操作链,对数据源的数据进行处理
-
4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用
-
测试 Stream 的实例化
-
@author shkstart
-
@create 2019 下午 4:25
*/
public class StreamAPITest {
// 创建 Stream 方式一:通过集合
@Test
public void test1(){
List<Employee> employees = EmployeeData.getEmployees();
// default Stream<E> stream() : 返回一个顺序流
Stream<Employee> stream = employees.stream();
// default Stream<E> parallelStream() : 返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();
}
<span class="hljs-comment">//创建 Stream方式二:通过数组</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test2</span><span class="hljs-params">()</span>{
<span class="hljs-type">int</span>[] arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">int</span>[]{<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>};
<span class="hljs-comment">//调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流</span>
<span class="hljs-type">IntStream</span> <span class="hljs-variable">stream</span> <span class="hljs-operator">=</span> Arrays.stream(arr);
<span class="hljs-type">Employee</span> <span class="hljs-variable">e1</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1001</span>,<span class="hljs-string">"Tom"</span>);
<span class="hljs-type">Employee</span> <span class="hljs-variable">e2</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1002</span>,<span class="hljs-string">"Jerry"</span>);
Employee[] arr1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}
<span class="hljs-comment">//创建 Stream方式三:通过Stream的of()</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test3</span><span class="hljs-params">()</span>{
Stream<Integer> stream = Stream.of(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>);
}
<span class="hljs-comment">//创建 Stream方式四:创建无限流</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test4</span><span class="hljs-params">()</span>{
// 迭代
// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
// 遍历前 10 个偶数
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
}
8.3、Stream 的中间操作
package com.atguigu.java3;
import com.atguigu.java2.Employee;
import com.atguigu.java2.EmployeeData;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
-
测试 Stream 的中间操作
-
@author shkstart
-
@create 2019 下午 4:42
*/
public class StreamAPITest1 {
//1- 筛选与切片
@Test
public void test1(){
List<Employee> list = EmployeeData.getEmployees();
// filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
Stream<Employee> stream = list.stream();
// 练习:查询员工表中薪资大于 7000 的员工信息
stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);
System.out.println();
// limit(n)——截断流,使其元素不超过给定数量。
list.stream().limit(3).forEach(System.out::println);
System.out.println();
// skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
list.stream().skip(3).forEach(System.out::println);
System.out.println();
// distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1010</span>,<span class="hljs-string">"刘强东"</span>,<span class="hljs-number">40</span>,<span class="hljs-number">8000</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1010</span>,<span class="hljs-string">"刘强东"</span>,<span class="hljs-number">41</span>,<span class="hljs-number">8000</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1010</span>,<span class="hljs-string">"刘强东"</span>,<span class="hljs-number">40</span>,<span class="hljs-number">8000</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1010</span>,<span class="hljs-string">"刘强东"</span>,<span class="hljs-number">40</span>,<span class="hljs-number">8000</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Employee</span>(<span class="hljs-number">1010</span>,<span class="hljs-string">"刘强东"</span>,<span class="hljs-number">40</span>,<span class="hljs-number">8000</span>));
// System.out.println(list);
list.stream().distinct().forEach(System.out::println);
}
<span class="hljs-comment">//映射</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test2</span><span class="hljs-params">()</span>{
// map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。
List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
// 练习 1:获取员工姓名长度大于 3 的员工的姓名。
List<Employee> employees = EmployeeData.getEmployees();
Stream<String> namesStream = employees.stream().map(Employee::getName);
namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
System.out.println();
// 练习 2:
Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);
streamStream.forEach(s ->{
s.forEach(System.out::println);
});
System.out.println();
// flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
characterStream.forEach(System.out::println);
}
<span class="hljs-comment">//将字符串中的多个字符构成的集合转换为对应的Stream的实例</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Stream<Character> <span class="hljs-title function_">fromStringToStream</span><span class="hljs-params">(String str)</span>{<span class="hljs-comment">//aa</span>
ArrayList<Character> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
<span class="hljs-keyword">for</span>(Character c : str.toCharArray()){
list.add(c);
}
<span class="hljs-keyword">return</span> list.stream();
}
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test3</span><span class="hljs-params">()</span>{
<span class="hljs-type">ArrayList</span> <span class="hljs-variable">list1</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>();
list1.add(<span class="hljs-number">1</span>);
list1.add(<span class="hljs-number">2</span>);
list1.add(<span class="hljs-number">3</span>);
<span class="hljs-type">ArrayList</span> <span class="hljs-variable">list2</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>();
list2.add(<span class="hljs-number">4</span>);
list2.add(<span class="hljs-number">5</span>);
list2.add(<span class="hljs-number">6</span>);
// list1.add(list2);
list1.addAll(list2);
System.out.println(list1);
}
<span class="hljs-comment">//3-排序</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test4</span><span class="hljs-params">()</span>{
// sorted()——自然排序
List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);
list.stream().sorted().forEach(System.out::println);
// 抛异常,原因:Employee 没有实现 Comparable 接口
// List<Employee> employees = EmployeeData.getEmployees();
// employees.stream().sorted().forEach(System.out::println);
// sorted(Comparator com)——定制排序
List<Employee> employees = EmployeeData.getEmployees();
employees.stream().sorted( (e1,e2) -> {
<span class="hljs-type">int</span> <span class="hljs-variable">ageValue</span> <span class="hljs-operator">=</span> Integer.compare(e1.getAge(),e2.getAge());
<span class="hljs-keyword">if</span>(ageValue != <span class="hljs-number">0</span>){
<span class="hljs-keyword">return</span> ageValue;
}<span class="hljs-keyword">else</span>{
<span class="hljs-keyword">return</span> -Double.compare(e1.getSalary(),e2.getSalary());
}
}).forEach(System.out::println);
}
}
8.4、Stream 的终止操作
package com.atguigu.java3;
import com.atguigu.java2.Employee;
import com.atguigu.java2.EmployeeData;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
-
测试 Stream 的终止操作
-
@author shkstart
-
@create 2019 下午 6:37
*/
public class StreamAPITest2 {
//1- 匹配与查找
@Test
public void test1(){
List<Employee> employees = EmployeeData.getEmployees();
// allMatch(Predicate p)——检查是否匹配所有元素。
// 练习:是否所有的员工的年龄都大于 18
boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
System.out.println(allMatch);
// anyMatch(Predicate p)——检查是否至少匹配一个元素。
// 练习:是否存在员工的工资大于 10000
boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
System.out.println(anyMatch);
// noneMatch(Predicate p)——检查是否没有匹配的元素。
// 练习:是否存在员工姓“雷”
boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
System.out.println(noneMatch);
// findFirst——返回第一个元素
Optional<Employee> employee = employees.stream().findFirst();
System.out.println(employee);
// findAny——返回当前流中的任意元素
Optional<Employee> employee1 = employees.parallelStream().findAny();
System.out.println(employee1);
}
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test2</span><span class="hljs-params">()</span>{
List<Employee> employees = EmployeeData.getEmployees();
<span class="hljs-comment">// count——返回流中元素的总个数</span>
<span class="hljs-type">long</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> employees.stream().filter(e -> e.getSalary() > <span class="hljs-number">5000</span>).count();
System.out.println(count);
// max(Comparator c)——返回流中最大值
// 练习:返回最高的工资:
Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
Optional<Double> maxSalary = salaryStream.max(Double::compare);
System.out.println(maxSalary);
// min(Comparator c)——返回流中最小值
// 练习:返回最低工资的员工
Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(employee);
System.out.println();
// forEach(Consumer c)——内部迭代
employees.stream().forEach(System.out::println);
<span class="hljs-comment">//使用集合的遍历操作</span>
employees.forEach(System.out::println);
}
<span class="hljs-comment">//2-归约</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test3</span><span class="hljs-params">()</span>{
// reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
// 练习 1:计算 1-10 的自然数的和
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
// reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
// 练习 2:计算公司所有员工工资的总和
List<Employee> employees = EmployeeData.getEmployees();
Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
// Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2);
System.out.println(sumMoney.get());
}
<span class="hljs-comment">//3-收集</span>
<span class="hljs-meta">@Test</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">test4</span><span class="hljs-params">()</span>{
// collect(Collector c)——将流转换为其他形式。接收一个 Collector 接口的实现,用于给 Stream 中元素做汇总的方法
// 练习 1:查找工资大于 6000 的员工,结果返回为一个 List 或 Set
List<Employee> employees = EmployeeData.getEmployees();
List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > <span class="hljs-number">6000</span>).collect(Collectors.toList());
employeeList.forEach(System.out::println);
System.out.println();
Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > <span class="hljs-number">6000</span>).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);
}
}