在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());//查看結果
通過removeIf
和lambda
表達式改寫,原本6行的代碼瞬間變成了一行!
運行結果:
[Person{name=‘張三’, age=22, gender=‘男’}, Person{name=‘李四’, age=19, gender=‘女’}, Person{name=‘田七’, age=25, gender=‘女’}]
Process finished with exit code 0
30歲以上的王五和趙六都被過濾掉了。
當然,如果對lambda
表達式不熟悉的話,也可以使用不用lambda
的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(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