快捷搜索: 王者荣耀 脱发

Java8对List集合中的数据进行过滤处理

0.需求场景

假设有这样一个需求,将List中所有超过 35 岁的员工剔除,该如何实现呢?我们可以利用 Java8 的流式编程,轻松的实现这个需求。

当然也不局限与上述场景,对应的处理方法适用与根据 List 中元素或元素的属性,对 List 进行处理的场景。

1.编码实现

首先定义一个 Employee 类,此类包含 name 和 age 两个属性。同时自动生成构造方法、 get 方法、set 方法和 toString 方法。

public class Employee {

    private String name;
    private int age;

    public Employee() {
    }

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
            "name=" + name +  +
            ", age=" + age +
            };
    }
}

首先循环创建 10 个 Employee 对象,组装成原始的 List 。随后对 List 中的每一个数控调用 whoDismiss 方法,过滤掉对应条件的数据。

public class Main {

    public static void main(String[] args) {
        List<Employee> employeeList = new ArrayList<>();
        for (int i = 30; i < 40; i++) {
            employeeList.add(new Employee("张" + i, i));
        }
        //将每个Employee对象传入whoDismiss方法进行处理,处理完成后过滤空元素,最后转换为List
        List<Employee> dismissEmployee = employeeList.stream()
            .map(Main::whoDismiss).filter(Objects::nonNull).collect(Collectors.toList());

        dismissEmployee.forEach(employee -> System.out.println(employee.toString()));
    }

    /**
     * 设置条件,对List中的元素进行处理
     *
     * @param employee
     * @return
     */
    public static Employee whoDismiss(Employee employee) {
        if (employee.getAge() > 35) {
            return null;
        } else {
            return employee;
        }
    }
}
经验分享 程序员 微信小程序 职场和发展