java8中集合新增的方法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一樣,只不過代碼量多了一些。

 

參考文章:

https://blog.csdn.net/qq_33829547/article/details/80277956


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM