Let's consider a Parent
class which contains only one Integer
attribute.
I created 6 objects of parent class and with one null variable. Then I added these objects to a list.
I want to retrieve the corresponding object by the value of Integer
attribute.
I used Java 8 Streams for it.
Predicate<Parent> predicate = e -> e.getId() == 100; // sample attribute value
result = list.stream().filter(predicate).collect(Collectors.toList());
But I got NullPointerException
, so I edited the code:
list.stream().filter(h -> h!=null).filter(predicate).collect(Collectors.toList());
But I want to throw an exception if any of the object is null. If no objects in the list is null, then I want to retrieve the corresponding object from list.
How can I achieve this using a single statement using Java 8 Streams?
null
values then?Parent
in the list.catch(NullPointerException ex){ if(list.contains(null)) throw new CustomException(); else throw ex; }
, that way other NPEs are retained. The check has some costs but that doesn’t matter as it is only performed in the erroneous case.e.getId()
happen to return a nullInteger
.