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

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

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

  1. public class EmployeeTest {
  2. public static void main(String[] args) {
  3. List<Employee> empList = new ArrayList<>();
  4. createEmpList(empList);
  5. List<Integer> employeeIds = empList.stream()
  6. .filter(x -> x.getName().length() > 3)
  7. .map(x -> x.getId())
  8. .collect(Collectors.toList());
  9. System.out.println(employeeIds);
  10. }
  11. private static void createEmpList(List<Employee> empList) {
  12. Employee e1 = new Employee("siddu", 1, "Hyderabad", 70000);
  13. Employee e2 = new Employee("Swami", 2, "Hyderabad", 50000);
  14. Employee e3 = new Employee("Ramu", 3, "Bangalore", 100000);
  15. Employee e4 = new Employee(null, 4, "Hyderabad", 65000);
  16. Employee e5 = new Employee("Krishna", 5, "Bangalore", 160000);
  17. Employee e6 = new Employee("Naidu", 6, "Poland", 250000);
  18. Employee e7 = new Employee("Arun", 7, "Pune", 45000);
  19. Employee e8 = new Employee("Mahesh", 8, "Chennai", 85000);
  20. empList.add(e1);
  21. empList.add(e2);
  22. empList.add(e3);
  23. empList.add(e4);
  24. empList.add(e5);
  25. empList.add(e6);
  26. empList.add(e7);
  27. empList.add(e8);
  28. }
  29. }
x7yiwoj4

x7yiwoj41#

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

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

esbemjvw2#

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

  1. List<Employee> empList = new ArrayList<>();
  2. createEmpList(empList);
  3. List<Integer> employeeIds = empList.stream().filter(x -> {
  4. try {
  5. return x.getName().length() > 3;
  6. } catch (Exception e) {
  7. return false;
  8. }
  9. }).map(x -> x.getId()).collect(Collectors.toList());
  10. System.out.println(employeeIds);

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

相关问题