我们在 Java 开发中经常会遇到需要根据特定条件过滤集合数据的情况。Java 的 ArrayList 提供了一个非常方便的 removeIf() 方法,允许我们一次性移除所有满足给定 谓词(Predicate) 过滤条件的元素。我们只需将表示判断条件的谓词作为参数传递给该方法即可。需要注意的是,如果在迭代过程中或由谓词抛出了任何运行时异常,这些异常都会直接传递给调用者处理。
removeIf() 方法利用 Java 8 的 Predicate 函数式接口 来定义移除元素的具体逻辑,使得代码更加简洁和易读。
示例 1
在这个例子中,让我们来看看如何使用 removeIf() 方法 从一个整数 ArrayList 中移除所有能被 3 整除的数字*。
// Java program to demonstrate the use of removeIf()
// method with ArrayList of Integers
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// create an ArrayList of integers
ArrayList num = new ArrayList();
// Adding numbers to
// the ArrayList
num.add(23);
num.add(32);
num.add(45);
num.add(63);
// Using removeIf() method to remove
// numbers divisible by 3
num.removeIf(n -> (n % 3 == 0));
System.out.println(num);
}
}
Output
[23, 32]
ArrayList removeIf() 方法的语法
> boolean removeIf(Predicate filter)
- 参数:该方法接受一个名为 "
filter" 的参数,用于指定移除元素的条件。 - 返回类型:如果移除了任何元素,该方法返回 INLINECODE0d6abda5;否则返回 INLINECODE5c050e7f。
- 异常:如果指定的过滤器为 null,该方法将抛出 NullPointerException。
Java ArrayList removeIf() 方法的更多示例
示例 2: 在这里,我们将使用 removeIf() 方法 从字符串 ArrayList 中移除所有以字母 ‘S‘ 开头的名称*。
// Java program to demonstrate the use of removeIf()
// method with ArrayList of Strings
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Creating an ArrayList of student names
ArrayList s = new ArrayList();
// Adding student names to the ArrayList
s.add("Sweta");
s.add("Gudly");
s.add("Sohan");
s.add("Amiya");
s.add("Ram");
// Using removeIf() method to
// remove names starting with ‘S‘
s.removeIf(name -> name.startsWith("S"));
System.out.println("Students whose names do not start with S:");
System.out.println(s);
}
}
Output
Students whose names do not start with S:
[Gudly, Amiya, Ram]