- 准备的bean类
public class Employee {
private String name;
private int age;
private double salary;
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 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 String toString() {
return "Employee{" +
"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;
Employee employee = (Employee) o;
return age == employee.age &&
Double.compare(employee.salary, salary) == 0 &&
name.equals(employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, salary);
}
}
其中equals与hashCode是为了去重
添加值
Listemployees=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) );
stream要终止操作财执行,不然就不执行
过滤:这里是过滤,返回大于35的age值
//中间操作,不会执行
Stream stream = employees.stream().filter((e) -> {
System.out.println("Stream API 的中间操作");
return e.getAge()>35;//返回age大于35的
});
//终止操作:一次性全部内容,即惰性求值
stream.forEach(System.out::println);
limit(2)表示限制,限制流的数量为2,取前面两个,这个会执行两次
@Test
public void test2(){
employees.stream()
.filter((e)->{
System.out.println("短路!");
return e.getSalary()>5000;
})
.limit(2)//执行两次
.forEach(System.out::println);
}
skip:表示跳过,前面的值,取后面的,这个会执行全部
//跳skip
@Test
public void test3(){
employees.stream()
.filter((e)->{
System.out.println("短路!");
return e.getSalary()>5000;
})
.skip(2)//执行了5次
.forEach(System.out::println);
}
distinct不同的,不能够一样
@Test
public void test4(){
employees.stream()
.filter((e)->{
System.out.println("去重");
return e.getSalary()>5000;
})
.distinct()
.forEach(System.out::println);
}
2.反思总结
limit 与skip是互补关系



