Let's consider a Parent class which contains only one Integer attribute. I created 6 objects of parent class and values of attribute are 100, 20, 300, 400, 500, null.
Now I added all the objects to a list(Name of list is list). Then I want to get the objects whose attribute value is greater than 100. I used Java 8 streams for this purpose.
Predicate<Entity> predicate = e -> e.getParentId() < 100;
result = list.stream().filter(predicate).collect(Collectors.toList());
I also want to sort the list in descending order. I used the following code for this purpose.
Comparator<Entity> comp = (d1,d2) -> d2.getId().compareTo(d1.getId());
list.sort(comp);
In both cases I get a NullPointerException.
How to handle this?
ethat isnull, ore.getParentId()? Ife.getParentId()is declared as anInteger(the boxed type), it may be null. But then when it's converted to anintto compare it to 100, the result will be aNullPointerExceptionif it'snull.