Java集合Stream类filter的使⽤
之前的⼀⽂写了使⽤removeIf来实现按条件对集合进⾏过滤。这篇⽂章使⽤同样是JDK1.8新加⼊的Stream中filter⽅法来实现同样的效果。并且在实际项⽬中通常使⽤filter更多。关于Stream的详细介绍参见。
同样的场景:你是公司某个岗位的HR,收到了⼤量的简历,为了节约时间,现需按照⼀点规则过滤⼀下这些简历。⽐如要经常熬夜加班,所以只招收男性。
//求职者的实体类
public class Person {
private String name;//姓名
private Integer age;//年龄
private String gender;//性别
...
/
/省略构造⽅法和getter、setter⽅法
...
//重写toString,⽅便观看结果
@Overridejava stream
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
这⾥就不展⽰使⽤传统Iterator来进⾏过滤了,有需要做对⽐的可以参见之前的。
使⽤Stream的filter进⾏过滤,只保留男性的操作:
Collection<Person> collection = new ArrayList();
collection.add(new Person("张三", 22, "男"));
collection.add(new Person("李四", 19, "⼥"));
collection.add(new Person("王五", 34, "男"));
collection.add(new Person("赵六", 30, "男"));
collection.add(new Person("⽥七", 25, "⼥"));
Stream<Person> personStream = collection.stream().filter(new Predicate<Person>() {
@Override
public boolean test(Person person) {
return "男".Gender());//只保留男性
}
});
collection = List());//将Stream转化为List
System.out.String());//查看结果
运⾏结果如下:
[Person{name=‘张三’, age=22, gender=‘男’}, Person{name=‘王五’, age=34, gender=‘男’}, Person{name=‘赵六’, age=30,
gender=‘男’}]
Process finished with exit code 0
上⾯的demo没有使⽤lambda表达式,下⾯的demo使⽤lambda来进⼀步精简代码:
Collection<Person> collection = new ArrayList();
collection.add(new Person("张三", 22, "男"));
collection.add(new Person("李四", 19, "⼥"));
collection.add(new Person("王五", 34, "男"));
collection.add(new Person("赵六", 30, "男"));
collection.add(new Person("⽥七", 25, "⼥"));
Stream<Person> personStream = collection.stream().filter(
person -> "男".Gender())//只保留男性
);
collection = List());//将Stream转化为List
System.out.String());//查看结果
效果和不⽤lambda是⼀样的。
不过读者在使⽤filter时不要和removeIf弄混淆了:
removeIf中的test⽅法返回true代表当前元素会被过滤掉;
filter中的test⽅法返回true代表当前元素会保留下来。