Handling null in java streams with optional

  • A+
Category:Languages

What would be the best way of handling null if we have senario like below

//mocking for demonstraton   studentsByCourseRoster.setUsers(null);  studentsByCourseRoster.getUsers().stream().forEach(user -> {     final UserDTOv2 userDTO = new UserDTOv2();     userDTO.populateUserDataFromUserDTO(user, groupedUsers);     users.add(userDTO); }); 

 


If you want to retain the single statement structure, you could use Optional.ofNullable and replace null with an empty list:

Optional.ofNullable(studentsByCourseRoster.getUsers())         .orElse(Collections.emptyList()).stream()         .forEach(user -> {                      final UserDTOv2 userDTO = new UserDTOv2();                      userDTO.populateUserDataFromUserDTO(user, groupedUsers);                      users.add(userDTO);          }); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: