Java8之Stream API
程序员文章站
2022-05-05 08:57:59
...
Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API对集合数据进行操作,就类似于使用SQL执行数据库查询。也可以使用Stream API进行并行执行操作。简而言之,Stream API提供了一种高效且易于使用的处理数据的方式。
Stream(流)是数据渠道,用于操作数据源(集合、数组等)所生成的元素列表。Stream不会存储元素,不会改变源对象,相反,它们会返回一个持有结果的新Stream。Stream操作是延迟执行的,这意味着它们会等到需要结果的时候才执行。
Stream操作的三个步骤
(1)创建Stream:一个数据源获取一个流
(2)中间操作:对数据源的数据进行处理
(3)终止操作:执行中间的操作链,并产生结果
package com.alisa.java8.entity;
public class Employee {
private int id;
private String name;
private int age;
private double salary;
public Employee() {
}
public Employee(String name) {
this.name = name;
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = 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 String show() {
return "测试方法引用!";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) 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(salary) != Double.doubleToLongBits(other.salary))
return false;
return true;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
}
package com.alisa.java8.entity;
public class Employee1 {
private int id;
private String name;
private int age;
private double salary;
private Status status;
public Employee1() {
}
public Employee1(String name) {
this.name = name;
}
public Employee1(String name, int age) {
this.name = name;
this.age = age;
}
public Employee1(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public Employee1(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 "测试方法引用!";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee1 other = (Employee1) 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(salary) != Double.doubleToLongBits(other.salary))
return false;
return true;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status
+ "]";
}
public enum Status {
FREE, BUSY, VOCATION;
}
}
package com.alisa.java8.stream;
import com.alisa.java8.entity.Employee;
import com.alisa.java8.entity.Employee1;
import com.alisa.java8.entity.Employee1.Status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* 一、Stream API操作步骤
* 1、创建Stream
* 2、中间操作
* 3、终止操作
* */
@RunWith(SpringRunner.class)
@SpringBootTest
public class StreamAPITest1 {
//1、创建Stream
@Test
public void test1(){
//(1)Collection提供了两个方法:stream()和parallelStream()
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream(); //获取一个顺序流
Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
//(2)通过Arrays中的stream()获取一个数组流
Integer[] nums = new Integer[10];
Stream<Integer> arrayStream = Arrays.stream(nums);
//(3)通过Stream类中静态方法of()
Stream<Integer> ofStream = Stream.of(1,2,3,4,5,6);
//(4)创建无限流
Stream<Integer> infiniteStream = Stream.iterate(0,(x) -> x + 2).limit(10);
//生成
Stream<Double> generateStream = Stream.generate(Math::random).limit(10);
generateStream.forEach(System.out::println);
}
//2、中间操作
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);
/*
* (1)筛选与切片
* filter——接收Lambda,从流中排除某些元素
* limit——截断流,使其元素不超过给定数量
* skip(n)——跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补
* distinct——筛选,通过流所生成元素的hashCode()和equals()去除重复元素,需要重写以上两个方法
* */
//内部迭代:迭代操作Stream API内部完成
@Test
public void test2(){
//所有的中间操作不会做任何处理
Stream<Employee> stream = emps.stream()
.filter((emp) -> {
System.out.println("测试中间操作");
return emp.getAge() <= 35;
});
//只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
stream.forEach(System.out::println);
}
//外部迭代
@Test
public void test3(){
Iterator<Employee> it = emps.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
@Test
public void test4(){
emps.stream()
.filter((emp) -> {
System.out.println("短路");//达到limit的数量后,不会再进行查找
return emp.getSalary() >= 5000;
}).limit(3)
.forEach(System.out::println);
}
@Test
public void test5(){
emps.stream()
.filter((emp) -> emp.getSalary() >= 5000)
.skip(2)
.forEach(System.out::println);
}
@Test
public void test6(){
emps.stream()
.distinct()
.forEach(System.out::println);
}
/*
* (2)映射
* map——接收Lambda,将元素转换成其他形式或提取信息,接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
* flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
* */
@Test
public void test7(){
Stream<String> stream1 = emps.stream()
.map((e) -> e.getName());
stream1.forEach(System.out::println);
System.out.println("========================");
List<String> stringList = Arrays.asList("Lambda","hello","world");
Stream<String> stream2 = stringList.stream()
.map((e) -> e.toUpperCase());
stream2.forEach(System.out::println);
}
@Test
public void test8(){
List<String> stringList = Arrays.asList("Lambda","hello","world");
Stream<Stream<Character>> stream1 = stringList.stream()
.map(StreamAPITest1::filterCharacter);
stream1.forEach((stream) -> stream.forEach(System.out::println));
System.out.println("========================");
Stream<Character> stream2 = stringList.stream()
.flatMap(StreamAPITest1::filterCharacter);
stream2.forEach(System.out::println);
}
public static Stream<Character> filterCharacter(String str){
List<Character> charList = new ArrayList<>();
for (char ch:str.toCharArray()) {
charList.add(ch);
}
return charList.stream();
}
/*
* (3)排序
* sorted——自然排序
* sorted(Comparator com)——定制排序
* */
@Test
public void test9(){
emps.stream()
.map(Employee::getName)
.sorted()
.forEach(System.out::println);
System.out.println("========================");
emps.stream()
.sorted((x,y) -> {
if(x.getAge() == y.getAge()){
return x.getName().compareTo(y.getName());
}else{
return Integer.compare(x.getAge(),y.getAge());
}
})
.forEach(System.out::println);
}
/*
* 3、终止操作
* allMatch——检查是否匹配所有元素
* anyMatch——检查是否至少匹配一个元素
* noneMatch——检查是否没有匹配的元素
* findFirst——返回第一个元素
* findAny——返回当前流中的任意元素
* count——返回流中元素的总个数
* max——返回流中最大值
* min——返回流中最小值
* reduce(T identity,BinaryOperator)/reduce(BinaryOperator)——归约:可以将流中元素反复结合起来,得到一个值
* collect——将流转换为其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
* */
List<Employee1> emps1 = Arrays.asList(
new Employee1(102, "李四", 59, 6666.66, Status.BUSY),
new Employee1(101, "张三", 18, 9999.99, Status.FREE),
new Employee1(103, "王五", 28, 3333.33, Status.VOCATION),
new Employee1(104, "赵六", 8, 7777.77, Status.FREE),
new Employee1(104, "赵六", 8, 7777.77, Status.FREE),
new Employee1(104, "赵六", 8, 7777.77, Status.FREE),
new Employee1(105, "田七", 38, 5555.55, Status.BUSY)
);
@Test
public void test10(){
System.out.println(emps1.stream()
.allMatch((e) -> e.getStatus().equals(Status.BUSY)));
System.out.println(emps1.stream()
.noneMatch((e) -> e.getStatus().equals(Status.BUSY)));
}
@Test
public void test11(){
Optional<Employee1> op1 = emps1.stream()
.sorted((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary())).findFirst();
System.out.println(op1.get());
System.out.println("========================");
Optional<Employee1> op2 = emps1.stream()
.filter((e) -> e.getStatus().equals(Status.BUSY))
.findAny();
System.out.println(op2.get());
}
@Test
public void test12(){
System.out.println(emps1.stream()
.filter((e) -> e.getStatus().equals(Status.BUSY))
.count());
Optional<Double> op1 = emps1.stream()
.map(Employee1::getSalary)
.max(Double::compare);
System.out.println(op1.get());
Optional<Employee1> op2 = emps1.stream()
.min((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));
System.out.println(op2.get());
}
//流进行终止操作后,不能再次使用
@Test
public void test13(){
Stream<Employee1> stream = emps1.stream()
.filter((e) -> e.getStatus().equals(Status.FREE));
System.out.println(stream.count());
System.out.println(stream.map(Employee1::getSalary).max(Double::compare));
//报错:java.lang.IllegalStateException: stream has already been operated upon or closed
}
@Test
public void test14(){
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);
Optional<Double> op = emps1.stream()
.map(Employee1::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
//搜索名字中“六”出现的次数
@Test
public void test15(){
Optional<Integer> count = emps1.stream()
.map(Employee1::getName)
.flatMap(StreamAPITest1::filterCharacter)
.map((ch) -> {
if (ch.equals('六')) {
return 1;
} else {
return 0;
}
}).reduce(Integer::sum);
System.out.println(count.get());
}
@Test
public void test16(){
List<String> nameList = emps1.stream()
.map(Employee1::getName)
.collect(Collectors.toList());
nameList.forEach(System.out::println);
System.out.println("======================================");
Set<String> nameSet = emps1.stream()
.map(Employee1::getName)
.collect(Collectors.toSet());
nameSet.forEach(System.out::println);
System.out.println("======================================");
HashSet<String> nameHSet = emps1.stream()
.map(Employee1::getName)
.collect(Collectors.toCollection(HashSet::new));
nameHSet.forEach(System.out::println);
System.out.println("======================================");
}
@Test
public void test17(){
Optional<Double> maxSalary = emps1.stream()
.map(Employee1::getSalary)
.collect(Collectors.maxBy(Double::compare));
System.out.println(maxSalary.get());
System.out.println("======================================");
Optional<Employee1> maxEmp = emps1.stream()
.collect(Collectors.minBy((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary())));
System.out.println(maxEmp.get());
System.out.println("======================================");
Double sumSalary = emps1.stream()
.collect(Collectors.summingDouble(Employee1::getSalary));
System.out.println(sumSalary);
System.out.println("======================================");
Double avgSalary = emps1.stream()
.collect(Collectors.averagingDouble(Employee1::getSalary));
System.out.println(avgSalary);
System.out.println("======================================");
Long count = emps1.stream()
.collect(Collectors.counting());
System.out.println(count);
System.out.println("======================================");
DoubleSummaryStatistics collect = emps1.stream()
.collect(Collectors.summarizingDouble(Employee1::getSalary));
System.out.println(collect.getMax());
}
//分组
@Test
public void test18(){
Map<Status, List<Employee1>> map = emps1.stream()
.collect(Collectors.groupingBy(Employee1::getStatus));
System.out.println(map);
}
//多级分组
@Test
public void test19(){
Map<Status, Map<String, List<Employee1>>> map = emps1.stream()
.collect(Collectors.groupingBy(Employee1::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() >= 60) {
return "老年";
} else if (e.getAge() >= 35) {
return "中年";
} else {
return "青年";
}
})));
System.out.println(map);
}
//分区
@Test
public void test20(){
Map<Boolean, List<Employee1>> map = emps1.stream()
.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
System.out.println(map);
}
@Test
public void test21(){
String str = emps1.stream()
.map(Employee1::getName)
.collect(Collectors.joining(",","===","==="));
System.out.println(str);
}
@Test
public void test22(){
Optional<Double> sum = emps1.stream()
.map(Employee1::getSalary)
.collect(Collectors.reducing(Double::sum));
System.out.println(sum.get());
}
//练习1:给定一个数字列表,如何返回一个由每个数的平方构成的列表呢
@Test
public void exercise1(){
List<Integer> numList = Arrays.asList(1,2,3,4,5);
numList.stream()
.map((x) -> x * x)
.forEach(System.out::println);
}
//练习2:怎样用map和reduce方法数一数流中有多少个Employee1
@Test
public void exercise2(){
Optional<Integer> count = emps1.stream()
.map((e) -> 1)
.reduce(Integer::sum);
System.out.println(count.get());
}
}