I know the subject may be a bit in advance
as the JDK8 is not yet released (and not for now anyway..) but I was reading some articles about the Lambda expressions and particularly the part related to the new collection API known as Stream.
Here is the example as given in the Java Magazine article (it is an otter population algorithm..):
Set<Otter> otters = getOtters(); System.out.println(otters.stream() .filter(o -> !o.isWild()) .map(o -> o.getKeeper()) .filter(k -> k.isFemale()) .into(new ArrayList<>()) .size());
My question is what happen if in the middle of the Set internal iteration, one of the otter is null?
I would expect a NullPointerException to be thrown but maybe am I still stuck in the previous development paradigm (non-functional), can someone enlighten me as how this should be handled?
If this really throw a NullPointerException, I find the feature quite dangerous and will have to be used only as below:
What is the best option, or any other option?
We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.
Designers of the API did not want to assume whether null means the value is not present (absent value) or is present but equals null. Also, you can still use map(Optional::isNullable) on any stream.
1.1 Java Stream Filter or using the static nonNull() method provided by the java. util. Objects class. This method returns true if the allocated reference is not null, otherwise false.
Although the answers are 100% correct, a small suggestion to improve null
case handling of the list itself with Optional:
List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff) .orElseGet(Collections::emptyList) .stream() .filter(Objects::nonNull) .collect(Collectors.toList());
The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList)
will allow you to handle nicely the case when listOfStuff
is null and return an emptyList instead of failing with NullPointerException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With