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



这里的主要任务是检索姓名长度>3.但员工4的名称为null,因此将引发null指针异常。如何跳过员工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);
}
}

您可以像这样添加过滤器.filter(x-> x.getName() != null)

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

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

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]

最新更新