Stream是数据渠道,用于操作集合、数组等。
集合讲的是数据,Stream讲的是计算,即Stream是对集合的一系列操作过程。
注意:
1、Stream不会自己存储元素
2、Stream不会改变源对象,它会返回一个持有操作结果的新Stream
3、Stream操作是延迟执行的,这意味着他们会等到需要结果的时候才执行
Employee实体类,后面会用到
package com.lee.jdk.Entity;
import java.util.Objects;
public class Employee {
private Integer id;
private String name;
private int age;
private Double salary;
private Status status;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
public Employee(Integer 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 Employee(Integer id, String name, int age, Double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public enum Status{
FREE,BUSY,VACATION
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
", status=" + status +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age &&
Objects.equals(id, employee.id) &&
Objects.equals(name, employee.name) &&
Objects.equals(salary, employee.salary);
}
@Override
public int hashCode() {
return Objects.hash(id, name, age, salary);
}
}
Stream语法规则 一
package com.lee.jdk.stream;
import com.lee.jdk.Entity.Employee;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
/**
* 一、Stream的三个操作步骤:
* 1、创建Stream
* 2、中间操作
* 3、终止操作
*
* 二、创建Stream
* 1、Collection
* 2、Arrays
* 3、Stream的of
* 4、Stream的Iterate和Generate创建无限流
*
* 三、中间操作
* 1、筛选 和 切片
* filter : 接受lambda,并排除某些元素
* limit : 截断流,使其元素不超过给定数量
* skip(n) : 跳过元素,返回一个扔掉了前N个元素的流。若流中元素不足N个,则返回一个空流。
* distinct : 筛选,通过流生成元素的hashCode和equals去除重复元素
* 2、映射
* map:会将集合中的数据,一个个的应用于map的函数上
* flatMap : 会将集合中的数据,一个个的应用于map的函数上.并且将流中的每一个值换成另一个流,然后把所有流连成一个流
*
* 3、排序
* sorted 自然排序
* sorted(Comparator comp) 自定义排序
*/
public class TestStreamApi1 {
List<Employee> employeeList = Arrays.asList(
new Employee(1,"张三",25,17000d),
new Employee(2,"李四",18,19000d),
new Employee(3,"王五",55,7000d),
new Employee(4,"赵六",39,12000d),
new Employee(5,"刘七",28,14000d),
new Employee(5,"刘七",28,14000d),
new Employee(5,