0

Here is the sample code which I am trying to execute: Consider a list of Employees with List of Address.

employees.getAddresses.stream()
.filter(address -> address.getPincode!=null).findFirst()
.orElseThrow(() {
    logger.error("Error message");//logging error message
    CustomException() exception = new CustomException();//constructing custom exception 
    return exception;
    });

But in the above code, if employees/addresses is null, it will throw NPE.I want to add a null check to employees and adresses field too and throw the same error which I am throwing in orElseThow block. is there a clean way of doing it. Is it possible to use the same "orElseThrow" for this null check.

  • 1
    If `address` is null, then you can't call `getPinCode`. – hfontanez Jul 13 '22 at 04:49
  • Also, this question has been asked before. Check answers for how to handle NPE and answers for Java streams. The answer you seek has been asked before. It is a matter of time before this question is closed for being a duplicate. – hfontanez Jul 13 '22 at 04:52
  • https://stackoverflow.com/questions/42424191/java-8-applying-stream-filter-based-on-a-condition –  Jul 13 '22 at 04:59
  • Thanks for you response. But what I was asking is for the list which we are iterating using stream api. If that is null and we have to check, what is the best way to do this. I can think of one way which is: //before calling stream on employees.addresses first do a null check and if null return empty stream otherwise sirectly use the stream to do the filter and throw exception. Stream addressStream; if(employees==null || employess.getAddresses()==null) { return Stream.empty(); } else { – user3891511 Jul 13 '22 at 06:25
  • 1
    The best way is not to let these things become `null`. Since `getAddresses()` returns a list, its default value should be an empty list, not `null`. It’s not clear what type `employees` has, but it’s always better not to let things be `null` in the first place, rather than clutter all subsequent processing with `null` checks. – Holger Jul 13 '22 at 09:51

0 Answers0