查看更多教程 https://on  itroad.com

ArrayList removeIf()方法 示例

Java 程序使用 removeIf()方法以谓词的形式删除与给定条件匹配的元素。

从数字列表中删除偶数

在这个简单的例子中,我们有一个奇数/偶数列表,我们从列表中删除所有偶数。

import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        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]

按字段值移除移除对象

在这个简单的例子中,我们有一个员工列表,我们将删除所有名字以 字符 P开头的员工。

import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.function.Predicate;
public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<Employee> employees = new ArrayList<>();

        employees.add(new Employee(1l, "JackLi", LocalDate.of(2018, Month.APRIL, 21)));
        employees.add(new Employee(4l, "BobRobert", LocalDate.of(2018, Month.APRIL, 22)));
        employees.add(new Employee(3l, "Piyush", LocalDate.of(2018, Month.APRIL, 25)));
        employees.add(new Employee(5l, "Lucie", 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=JackLi, dob=2018-04-21], 
	Employee [id=4, name=BobRobert, dob=2018-04-22], 
	Employee [id=5, name=Lucie, dob=2018-04-23]
]

ArrayList removeIf() 方法

removeIf()方法采用 Predicate 类型的单个参数。
Predicate 接口是一个函数接口,表示一个参数的条件(布尔值函数)。
它检查给定的参数是否满足条件。

public boolean removeIf(Predicate<? super E> filter);

方法参数过滤一个谓词,它为要删除的元素返回“真”。

如果删除了任何元素,则方法返回 true

如果谓词为“null”,则方法抛出“NullPointerException”。

Java ArrayList removeIf() 方法

ArrayList removeIf() 迭代列表并删除该列表中满足给定谓词的所有元素。

日期:2020-09-17 00:09:56 来源:oir作者:oir