Java集合Stream类filter的使用_黄嘉成的博客-CSDN博客
Java集合Stream类filter的使用
黄嘉成 2018-05-11 11:49:42 242767 收藏 116
分类专栏: Java高级编程 文章标签: java 集合 Stream filter 过滤
版权
Java高级编程
专栏收录该内容
4 篇文章0 订阅
订阅专栏
之前的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;//性别
...
//省略构造方法和getter、setter方法
...
//重写toString,方便观看结果
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
1
20
这里就不展示使用传统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());//将Stream转化为List
System.out.println(collection.toString());//查看结果
1
16
运行结果如下:
[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());//将Stream转化为List
System.out.println(collection.toString());//查看结果
1
效果和不用lambda是一样的。
不过读者在使用filter时不要和removeIf弄混淆了:
removeIf中的test方法返回true代表当前元素会被过滤掉;
filter中的test方法返回true代表当前元素会保留下来。
黄嘉成
关注
————————————————
版权声明:本文为CSDN博主「黄嘉成」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_33829547/article/details/80279488