@BeJay is right, it's a bad practice to use null values in that context. NPE should only appear in the context of a code error like any forgotten or failed instantiation, null cannot be use to hold a meaningful value ( data not found ). It's a bit like the benefits of banning the use of magic numbers.
public static void main(String[] args)
{
List<Integer> List1 = List.of( 3, 14, 15, 9, 26);
List<Integer> List2 = List.of( 5, 16, 3, 2, 1);
// intend to be use as a stack of "to scan" Lists
ArrayList<List<Integer>> parentList = new ArrayList<>( List.of(List1,List2));
Optional<Integer> multipleOfFour = Optional.empty();
//looping while parentList still contains sub-list(s) and no multiple of 4 was found
while ( ! parentList.isEmpty() && multipleOfFour.isEmpty())
{
//popping out first element of parentList
List<Integer> currentList = parentList.remove(0);
multipleOfFour = currentList.stream().filter(num->num%4 == 0).findFirst();
}
if ( ! multipleOfFour.isPresent())
{
//cheating in case no multiple of 4 was found in any of the 2 lists
multipleOfFour = Optional.of(Integer.valueOf(4));
}
// never use get() unless absolutely sure isPresent()
// would return true or an exception could be thrown
System.out.println("first multiple of 4 found: " + multipleOfFour.get());
}
Now if I didn't instantiate multipleOfFour with Optional.empty() when declared, a NPE will occur when attempting to call isEmpty() in the while loop condition, and I'll know for sure the error comes from the code itself.
On the other hand if multipleOfFour.isPresent() doesn't return true when I expect, I'll know for sure the error comes either from the data provided or from the stream lambda that doesn't operate properly.
Easier to debug when you know where to look...
That Opened my eyes, I rewrote the method of recursive search I was working on, using Optional.empty() instead of null. Thank you @BeJay