|
之前的Java集合中removeIf的使用一文写了使用removeIf来实现按条件对集合进行过滤。这篇文章使用同样是JDK1.8新加入的Stream中filter方法来实现同样的效果。并且在实际项目中通常使用filter更多。关于Stream的详细介绍参见Java 8系列之Stream的基本语法详解。
同样的场景:你是公司某个岗位的HR,收到了大量的简历,为了节约时间,现需按照一点规则过滤一下这些简历。比如要经常熬夜加班,所以只招收男性。
public class Person {
private String name;
private Integer age;
private String gender;
...
...
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
这里就不展示使用传统Iterator来进行过滤了,有需要做对比的可以参见之前的Java集合中removeIf的使用。
使用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 "男".equals(person.getGender());
}
});
collection = personStream.collect(Collectors.toList());
System.out.println(collection.toString());
运行结果如下:
[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 -> "男".equals(person.getGender())
);
collection = personStream.collect(Collectors.toList());
System.out.println(collection.toString());
效果和不用lambda是一样的。
不过读者在使用filter时不要和removeIf弄混淆了:
removeIf中的test方法返回true代表当前元素会被过滤掉;
filter中的test方法返回true代表当前元素会保留下来。
|