文
章
目
录
章
目
录
Java 中的 ArrayList.removeIf()
方法通过迭代当前数组列表的元素并将它们与由参数 Predicate 指定的条件进行匹配来删除所有满足条件的元素。
// 快速指南
ArrayList<String> arraylist = new ArrayList<>(Arrays.asList("A", "B", "C", "C", "D"));
arraylist.removeIf(e -> e.equals("C")); //[A, B, D]
请注意,ArrayList 类还提供其他用于删除元素的方法,例如:
- remove():按值或索引位置删除单个元素。
- removeAll():按值删除所有指定元素的出现。
1.语法
removeIf()
接受一个类型为 Predicate 的单个参数。Predicate
接口是一个表示条件(布尔值函数)的函数接口,接受一个参数。它检查给定的参数是否满足条件。
public boolean removeIf(Predicate<? super E> filter);
- 方法参数:返回为需要被移除的元素返回
true
的过滤器谓词。 - 方法返回:如果从此列表中删除了任何元素,则返回
true
。 - 方法可能抛出:如果谓词为
null
,则可能抛出NullPointerException
。
2.删除符合条件的元素的示例
为了从数组列表中删除元素,我们可以使用 Predicate 实例以多种方式创建条件。让我们看看一些用例。
2.1. 从数字列表中删除所有偶数
在这个简单的示例中,我们有一个奇数和偶数数字列表。然后,我们使用 removeIf()
方法从列表中删除所有偶数。
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]
2.2. 删除具有匹配字段值的所有对象
在另一个示例中,我们有一个雇员列表。我们正在删除所有名字以字符 ‘P’ 开头的员工。
employee.getName().startsWith("P")
匹配每个员工的名字,如果名字以 ‘P’ 开头,则返回 true
。
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]
]
3.结论
removeIf()
方法是从数组列表中删除多个与特定条件匹配的元素的非常方便的方法。结合谓词和函数式编程的强大功能,此方法有助于创建这些用例的简洁可读代码。
这就是 Java 中的 ArrayList.removeIf()
的全部内容。