在JDK1.8中,Collection以及其子类新加入了removeIf方法,作用是按照一定规则过滤集合中的元素。
举例:Person类只有三个成员属性,分别是姓名name,年龄age和性别gender。现要过滤age大于等于40的求职者。
//求职者的实体类 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 + '\'' + '}'; } }
过滤:
Collection<Person> collection = new ArrayList(); collection.add(new Person("张三", 32, "男")); collection.add(new Person("李四", 19, "女")); collection.add(new Person("王五", 46, "男")); collection.add(new Person("赵六", 25, "男")); //过滤40岁以上的求职者 Iterator<Person> iterator = collection.iterator(); while (iterator.hasNext()) { Person person = iterator.next(); if (person.getAge() >= 40) iterator.remove(); } System.out.println(collection.toString());//查看结果
博客借鉴:https://blog.csdn.net/qq_33829547/article/details/80277956