Stream 流中间操作
filter 筛选limit 截断流skip(n) 跳过元素distinct 去重filter 筛选
筛选:接收 Lambda ,从流中排除某些元素。return为true时,元素会被保留
eg:筛选出大于35的并且工资大于6000的。
public class StreamFilter {List<Employee> employees = new ArrayList<>();{employees.add(new Employee(1,"张三",20,8895.31));employees.add(new Employee(2,"张四",28,7894.34));employees.add(new Employee(3,"张柳",46,6895.37));employees.add(new Employee(66,"王一",54,5895.5));employees.add(new Employee(56,"李四",55,4895.8));employees.add(new Employee(89,"李十一",32,9895.354));employees.add(new Employee(546,"张十五",20,18895.37));employees.add(new Employee(43,"刘十六",43,28895.35));employees.add(new Employee(43,"刘十六",43,28895.35));}/*** 测试Stream的Filter方法* 接收 Lambda ,从流中排除某些元素*/@Testpublic void testStreamFilter() {Stream<Employee> employeeStream = employees.stream().filter(employee -> {//保留大于35的并且工资大于6000的return employee.getAge() > 35 && employee.getSalary()>6000;});employeeStream.forEach(System.out::println);}}
result:
limit 截断流
截断:截断流,使其元素不超过给定数量
eg:limit(3)
/*** 测试Stream的limit方法* 截断流,使其元素不超过给定数量*/@Testpublic void testStreamFilter() {Stream<Employee> employeeStream = employees.stream().limit(3);employeeStream.forEach(System.out::println);}
result:
skip(n) 跳过元素
跳过:skip(n)
跳过元素
eg:跳过2个元素(使用场景:进行Excel导入时,第一行或者前两行通常是表头不需要操作)
/*** 测试Stream的Skip方法* 跳过元素,返回一个舍弃了前n个元素的流;若流中元素不足n个,则返回一个空流;与 limit(n) 互补* 从第二个元素得到两个元素*/@Testpublic void testStreamFilter() {Stream<Employee> employeeStream = employees.stream().skip(2);employeeStream.forEach(System.out::println);}
result:
distinct 去重
筛选去重:通过流所生成的hashCode()
与equals()
取除重复元素
eg:去除list
中的重复项
/*** 测试Stream的distinct方法* 筛选,通过流所生成的 hashCode() 与 equals() 取除重复元素* 去除重复项*/@Testpublic void testStreamFilter() {Stream<Employee> employeeStream = employees.stream().distinct();employeeStream.forEach(System.out::println);}
result: