筛选与切片:
filter —— 接收 Lambda,从流中排除某些元素;
limit —— 截断流,使其元素不超过给定数量;
skip(n) —— 跳过元素,返回一个仍掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补;
distinct —— 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素。
List<Employe> employes = Arrays.asList(
new Employe("张三", 18,9999.99),
new Employe("李四", 38,5555.99),
new Employe("王五", 50,6666.66),
new Employe("赵六", 16,3333.33),
new Employe("田七", 10,7777.77),
new Employe("田七", 10,7777.77),
new Employe("田七", 10,7777.77)
);
//filter 过滤
@Test
public void test1(){
employes.stream()//创建流
.filter(e->e.getAge() >= 35)//中间操作
.forEach(System.out::println);//终止操作
}
//limit 限制
@Test
public void test2(){
employes.stream()
.filter(e->e.getSalary() >= 5000)
.limit(2)
.forEach(System.out::println);
}
//skip(n) 跳过
@Test
public void test3(){
employes.stream()
.filter(e -> e.getSalary() >= 5000)
.skip(2)
.forEach(System.out::println);
}
//distinct 去重,通过hashCode() 和 equals() 去重
@Test
public void test4(){
employes.stream()
.distinct()
.forEach(System.out::println);
}
}
注意:distinct 去重的时候,Employee.java 中要覆写 equals() 和 hashCode() 方法:
package com.lambda1;
import java.util.Objects;
public class Employe {
private String name;
private int age;
private double salary;
public Employe() {
}
public Employe(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 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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employe employe = (Employe) o;
return age == employe.age &&
Double.compare(employe.salary, salary) == 0 &&
Objects.equals(name, employe.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, salary);
}
@Override
public String toString() {
return "Employe{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}