How return null by using Stream API?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How return null by using Stream API?



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


ArrayList


null



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 mach this two filters I will have NullPointerException. Haw can I get somethink like: return null?


return null





Don't. Instead, return an Optional and let the client decide what to do with it.
– Luiggi Mendoza
17 secs ago


Optional









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions