Java ArrayList removeIf() 方法
removeIf()
方法的语法是:
arraylist.removeIf(Predicate<E> filter)
这里,arraylist
是 ArrayList
类的一个对象。
removeIf() 参数
removeIf()
方法接受单一参数。
- filter - 决定是否移除一个元素
removeIf() 返回值
- 如果从 arraylist 中移除了元素,则返回
true
。
示例:从 ArrayList 中移除偶数
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// 创建一个 ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
// 向 ArrayList 添加元素
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
System.out.println("数字:" + numbers);
// 移除所有偶数
numbers.removeIf(e -> (e % 2) == 0);;
System.out.println("奇数:" + numbers);
}
}
输出
数字:[1, 2, 3, 4, 5, 6]
奇数:[1, 3, 5]
在上面的示例中,我们创建了一个名为 numbers
的 arraylist。注意这一行,
numbers.removeIf(e -> (e % 2) == 0);
这里,
e -> (e % 2) == 0)
是一个 lambda 表达式。它检查一个元素是否能被 2 整除。要了解更多,请访问 Java Lambda 表达式。removeIf()
- 如果e -> (e % 2) == 0
返回true
,则移除该元素。
示例 2:移除名称中包含 "land" 的国家
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// 创建一个 ArrayList
ArrayList<String> countries = new ArrayList<>();
// 向 ArrayList 添加元素
countries.add("Iceland");
countries.add("America");
countries.add("Ireland");
countries.add("Canada");
countries.add("Greenland");
System.out.println("国家:" + countries);
// 移除所有包含 "land" 的国家
countries.removeIf(e -> e.contains("land"));;
System.out.println("不包含 land 的国家:" + countries);
}
}
输出
国家:[Iceland, America, Ireland, Canada, Greenland]
不包含 land 的国家:[America, Canada]