How return null by using Stream API?

  • A+
Category:Languages

So, I have an ArrayList of autogenerated strings. I want to find the first element that contains some character or else if there is no one element that matches this filter, to apply another filter. In another way, I want to return null object.

So I write this lambda expression:

str.stream()    .filter(s -> s.contains("q"))    .findFirst()    .orElseGet(() -> str.stream()                        .filter(s -> s.contains("w"))                        .findFirst()                        .orElseGet(null)) 

But if there is no one element that matches this two filters I will have NullPointerException. How, can I get something like: return null?

 


Unless I'm missing something obvious, simply .orElse(null) instead of the last orElseGet. orElseGet accepts a Supplier and you pass a null, calling get() on a null reference, well...

Comment

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