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) {
// create an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
// add elements to the ArrayList
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
System.out.println("Numbers: " + numbers);
// remove all even numbers
numbers.removeIf(e -> (e % 2) == 0);;
System.out.println("Odd Numbers: " + numbers);
}
}
输出
Numbers: [1, 2, 3, 4, 5, 6] Odd Numbers: [1, 3, 5]
在上面的示例中,我们创建了一个名为 numbers 的 ArrayList。请注意这一行:
numbers.removeIf(e -> (e % 2) == 0);
这里,
e -> (e % 2) == 0)
是一个 lambda 表达式。它检查一个元素是否能被 2 整除。要了解更多信息,请访问 Java Lambda Expression。removeIf()
- 如果e -> (e % 2) == 0
返回true
,则移除该元素。
示例 2:移除名称中包含“land”的国家
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<String> countries = new ArrayList<>();
// add elements to the ArrayList
countries.add("Iceland");
countries.add("America");
countries.add("Ireland");
countries.add("Canada");
countries.add("Greenland");
System.out.println("Countries: " + countries);
// remove all even countries
countries.removeIf(e -> e.contains("land"));;
System.out.println("Countries without land: " + countries);
}
}
输出
Countries: [Iceland, America, Ireland, Canada, Greenland] Countries without land: [America, Canada]
在上面的示例中,我们使用了 Java String contains() 方法来检查元素是否包含“land”。这里:
e -> e.contains("land")
- 如果元素包含“land”,则返回true
removeIf()
- 如果e -> e.contains("land")
返回true
,则移除该元素。
另请阅读