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,方便观看结果 @Override 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 "男".equals(person.getGender());//只保留男性 } }); collection = personStream.collect(Collectors.toList());//将Stream转化为List 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());//将Stream转化为List System.out.println(collection.toString());//查看结果
效果和不用lambda是一样的。
不过读者在使用filter时不要和removeIf弄混淆了:
-
removeIf中的test方法返回true代表当前元素会被过滤掉; filter中的test方法返回true代表当前元素会保留下来。
上一篇:
IDEA上Java项目控制台中文乱码