当一个元素发生异常时,如何处理Java8流列表中的剩余元素?

ctrmrzij  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(418)

这里的主要任务是检索名称长度大于3的雇员的ID。但是雇员4的名称为null,因此将引发null指针异常。如何跳过引发异常并处理列表中剩余元素而不是终止列表的employee 4。期望的输出可以是[1、2、3、5、6、7、8]
代码如下:

public class EmployeeTest {
    public static void main(String[] args) {
        List<Employee> empList = new ArrayList<>();
        createEmpList(empList);
        List<Integer> employeeIds = empList.stream()
                .filter(x -> x.getName().length() > 3)
                .map(x -> x.getId())
                .collect(Collectors.toList());
        System.out.println(employeeIds);
    }

    private static void createEmpList(List<Employee> empList) {
        Employee e1 = new Employee("siddu",   1, "Hyderabad", 70000);
        Employee e2 = new Employee("Swami",   2, "Hyderabad", 50000);
        Employee e3 = new Employee("Ramu",    3, "Bangalore", 100000);
        Employee e4 = new Employee(null,      4, "Hyderabad", 65000);
        Employee e5 = new Employee("Krishna", 5, "Bangalore", 160000);
        Employee e6 = new Employee("Naidu",   6, "Poland",    250000);
        Employee e7 = new Employee("Arun",    7, "Pune",      45000);
        Employee e8 = new Employee("Mahesh",  8, "Chennai",   85000);

        empList.add(e1);
        empList.add(e2);
        empList.add(e3);
        empList.add(e4);
        empList.add(e5);
        empList.add(e6);
        empList.add(e7);
        empList.add(e8);
    }
}
x7yiwoj4

x7yiwoj41#

您只需添加过滤器 .filter(x-> x.getName() != null) 就像这样:

List<Employee> modifiedEmpList = empList.stream()
   .filter(x-> x.getName() != null)
   .filter(x -> x.getName().length() > 3)
   .collect(Collectors.toList());
esbemjvw

esbemjvw2#

下面的代码动态处理所有异常。谢谢

List<Employee> empList = new ArrayList<>();
        createEmpList(empList);
        List<Integer> employeeIds = empList.stream().filter(x -> {
            try {
                return x.getName().length() > 3;
            } catch (Exception e) {
                return false;
            }

        }).map(x -> x.getId()).collect(Collectors.toList());
        System.out.println(employeeIds);

输出: [1, 2, 3, 5, 6, 7, 8]

相关问题