Java集合Stream类filter的使用

之前的Java集合中removeIf的使用一文写了使用removeIf来实现按条件对集合进行过滤。这篇文章使用同样是JDK1.8新加入的Streamfilter方法来实现同样的效果。并且在实际项目中通常使用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 + '\'' +
                '}';
    }
}

这里就不展示使用传统Iterator来进行过滤了,有需要做对比的可以参见之前的Java集合中removeIf的使用
使用Streamfilter进行过滤,只保留男性的操作:

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代表当前元素会保留下来
  • 74
    点赞
  • 210
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄嘉成

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值