本文主要是介绍2.java8流的使用 stream的筛选与切片filter,limit,skip,distinct,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码
- 准备的bean类
/*** 创建日期:2021/10/29 14:01** @author tony.sun* 类说明:*/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;}@Overridepublic String toString() {return "Employee{" +"name='" + name + '\'' +", age=" + age +", salary=" + salary +'}';}
// 去重@Overridepublic 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);}@Overridepublic int hashCode() {return Objects.hash(name, age, salary);}
}
其中equals与hashCode是为了去重
添加值
List<Employee> employees=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<Employee> stream = employees.stream().filter((e) -> {System.out.println("Stream API 的中间操作");return e.getAge()>35;//返回age大于35的});//终止操作:一次性全部内容,即惰性求值stream.forEach(System.out::println);
limit(2)表示限制,限制流的数量为2,取前面两个,这个会执行两次
@Testpublic void test2(){employees.stream().filter((e)->{System.out.println("短路!");return e.getSalary()>5000;}).limit(2)//执行两次.forEach(System.out::println);}
skip:表示跳过,前面的值,取后面的,这个会执行全部
//跳skip@Testpublic void test3(){employees.stream().filter((e)->{System.out.println("短路!");return e.getSalary()>5000;}).skip(2)//执行了5次.forEach(System.out::println);}
distinct不同的,不能够一样
@Testpublic void test4(){employees.stream().filter((e)->{System.out.println("去重");return e.getSalary()>5000;}).distinct().forEach(System.out::println);}
2.反思总结
limit 与skip是互补关系
这篇关于2.java8流的使用 stream的筛选与切片filter,limit,skip,distinct的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!