removeIf()
方法的语法是:
arraylist.removeIf(Predicate<E> filter)
这里,
arraylist 是
ArrayList
类的对象。
removeIf() 参数
removeIf()
方法接受一个参数。
removeIf() 返回值
如果从数组列表中删除元素,则返回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 的数组列表。注意这一行,
numbers.removeIf(e-> (e % 2) == 0);
这里,
e->(e % 2) == 0)
是一个 lambda 表达式。它检查一个元素是否被 2 除。要了解更多信息,请访问 Java Lambda 表达式。
removeIf()
-如果 e->(e % 2) == 0
返回 true
,则删除元素。
示例 2: 删除名称中带有"土地"的国家
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
,则删除元素。