Java集合中removeIf的使用


在JDK1.8中,Collection以及其子類新加入了removeIf方法,作用是按照一定規則過濾集合中的元素。這里給讀者展示removeIf的用法。
首先設想一個場景,你是公司某個崗位的HR,收到了大量的簡歷,為了節約時間,現需按照一點規則過濾一下這些簡歷。比如這個崗位是低端崗位,只招30歲以下的求職者。

 1 Collection<Person> collection = new ArrayList();
 2 collection.add(new Person("張三", 22, "男"));
 3 collection.add(new Person("李四", 19, "女"));
 4 collection.add(new Person("王五", 34, "男"));
 5 collection.add(new Person("趙六", 30, "男"));
 6 collection.add(new Person("田七", 25, "女"));
 7 
 8 Stream<Person> personStream = collection.stream().filter(
 9         person -> "男".equals(person.getGender())//只保留男性
10 );
11 
12 collection = personStream.collect(Collectors.toList());//將Stream轉化為List
13 System.out.println(collection.toString());//查看結果

 

Person只有三個成員屬性,分別是姓名name,年齡age和性別gender。現要過濾age大於等於30的求職者。
下面是不用removeIf,而是使用Iterator的傳統寫法:

 1 Collection<Person> collection = new ArrayList();
 2 collection.add(new Person("張三", 22, "男"));
 3 collection.add(new Person("李四", 19, "女"));
 4 collection.add(new Person("王五", 34, "男"));
 5 collection.add(new Person("趙六", 30, "男"));
 6 collection.add(new Person("田七", 25, "女"));
 7 //過濾30歲以上的求職者
 8 Iterator<Person> iterator = collection.iterator();
 9 while (iterator.hasNext()) {
10     Person person = iterator.next();
11     if (person.getAge() >= 30)
12         iterator.remove();
13 }
14 System.out.println(collection.toString());//查看結果

 

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

 1 Collection<Person> collection = new ArrayList();
 2 collection.add(new Person("張三", 22, "男"));
 3 collection.add(new Person("李四", 19, "女"));
 4 collection.add(new Person("王五", 34, "男"));
 5 collection.add(new Person("趙六", 30, "男"));
 6 collection.add(new Person("田七", 25, "女"));
 7 
 8 
 9 collection.removeIf(
10     person -> person.getAge() >= 30
11 );//過濾30歲以上的求職者
12 
13 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,代碼如下:

 1 Collection<Person> collection = new ArrayList();
 2 collection.add(new Person("張三", 22, "男"));
 3 collection.add(new Person("李四", 19, "女"));
 4 collection.add(new Person("王五", 34, "男"));
 5 collection.add(new Person("趙六", 30, "男"));
 6 collection.add(new Person("田七", 25, "女"));
 7 
 8 collection.removeIf(new Predicate<Person>() {
 9     @Override
10     public boolean test(Person person) {
11         return person.getAge()>=30;//過濾30歲以上的求職者
12     }
13 });
14 
15 System.out.println(collection.toString());//查看結果

效果和用lambda一樣,只不過代碼量多了一些。

 

 

 

                                          


                   
          


免責聲明!

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



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