ArrayList removeIf() 迭代列表并移除此列表中满足给定谓词的所有元素。
removeIf()
方法采用Predicate 类型的单个参数。 Predicate 接口是一个功能接口,表示一个参数的条件(布尔值函数)。它检查给定的参数是否满足条件。
public boolean removeIf(Predicate<? super E> filter);
方法参数 – 过滤谓词,返回 true
用于要删除的元素。
方法返回 – $$$
如果删除了任何元素。
方法抛出 – true
如果谓词是 NullPointerException
。
Java 程序使用 removeIf()
方法以谓词的形式删除与给定条件匹配的元素。
在这个简单的示例中,我们有一个奇数/偶数列表,我们将从列表中删除所有偶数。
import java.util.ArrayList; import java.util.Arrays; public class ArrayListExample { public static void main(String[] args) throws CloneNotSupportedException { ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10)); numbers.removeIf( number -> number%2 == 0 ); System.out.println(numbers); } }
程序输出。
[1, 3, 5, 7, 9]
在这个简单的示例中,我们有一个员工列表,我们将删除所有名称以 char 'P'
开头的员工。
import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.function.Predicate; public class ArrayListExample { public static void main(String[] args) throws CloneNotSupportedException { ArrayList<Employee> employees = new ArrayList<>(); employees.add(new Employee(1l, "Alex", LocalDate.of(2018, Month.APRIL, 21))); employees.add(new Employee(4l, "Brian", LocalDate.of(2018, Month.APRIL, 22))); employees.add(new Employee(3l, "Piyush", LocalDate.of(2018, Month.APRIL, 25))); employees.add(new Employee(5l, "Charles", LocalDate.of(2018, Month.APRIL, 23))); employees.add(new Employee(2l, "Pawan", LocalDate.of(2018, Month.APRIL, 24))); Predicate<Employee> condition = employee -> employee.getName().startsWith("P"); employees.removeIf(condition); System.out.println(employees); } }
程序输出。
[ Employee [id=1, name=Alex, dob=2018-04-21], Employee [id=4, name=Brian, dob=2018-04-22], Employee [id=5, name=Charles, dob=2018-04-23] ]
以上就是 Java 中的 ArrayList removeIf() 方法。
快乐学习!!
更多参考:
Java ArrayList 指南
ArrayList Java 文档
谓词 Java 文档
标签2: Java ArrayList地址:https://www.cundage.com/article/arraylist-removeif.html