Java集合中removeIf的使用

在JDK1.8中,Collection以及其子类新加入了removeIf方法,作用是按照一定规则过滤集合中的元素。这里给读者展示removeIf的用法。
首先设想一个场景,你是公司某个岗位的HR,收到了大量的简历,为了节约时间,现需按照一点规则过滤一下这些简历。比如这个岗位是低端岗位,只招30岁以下的求职者。

//求职者的实体类
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 + '\'' +
                '}';
    }
}

Person类只有三个成员属性,分别是姓名name,年龄age和性别gender。现要过滤age大于等于30的求职者。
下面是不用removeIf,而是使用Iterator的传统写法:

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, "女"));
//过滤30岁以上的求职者
Iterator<Person> iterator = collection.iterator();
while (iterator.hasNext()) {
    Person person = iterator.next();
    if (person.getAge() >= 30)
        iterator.remove();
}
System.out.println(collection.toString());//查看结果

下面再看看使用removeIf的写法:

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, "女"));


collection.removeIf(
	person -> person.getAge() >= 30
);//过滤30岁以上的求职者

System.out.println(collection.toString());//查看结果

通过removeIflambda表达式改写,原本6行的代码瞬间变成了一行!
运行结果:

[Person{name=‘张三’, age=22, gender=‘男’}, Person{name=‘李四’, age=19, gender=‘女’}, Person{name=‘田七’, age=25, gender=‘女’}]
Process finished with exit code 0

30岁以上的王五和赵六都被过滤掉了。

当然,如果对lambda表达式不熟悉的话,也可以使用不用lambdaremoveIf,代码如下:

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, "女"));

collection.removeIf(new Predicate<Person>() {
    @Override
    public boolean test(Person person) {
	    return person.getAge()>=30;//过滤30岁以上的求职者
    }
});

System.out.println(collection.toString());//查看结果

效果和用lambda一样,只不过代码量多了一些。

  • 98
    点赞
  • 130
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黄嘉成

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

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

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

打赏作者

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

抵扣说明:

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

余额充值