Reputation: 31
What will be the equivalent lambda expression for below code?
List<String> List = new ArrayList<String>();
for (String var: alreadyList) {
try {
if (getNumber(var) == num) {
filteredList.add(var);
}
} catch(NullPointerException exception) {
throw exception;
}
}
getNumber
method throws Nullpointerexception
and the above code is also in a method which throws the same exception to a caller.This is usual lambda expression but how to throw the Nullpointerexception
in it?
List<String> List = alreadyList.stream()
.filter(var -> getNumber(var) == num)
.collect(Collectors.toList());
Upvotes: 2
Views: 128
Reputation: 44398
Never catch the unchecked exceptions including the NullPointerException
. The way you do is just rethrowing it. Either filter out the null
values out.
List<String> List = alreadyList.stream()
.filter(Objects::nonNull)
.filter(var -> getNumber(var) == num)
.collect(Collectors.toList());
The code you have provided:
List<String> List = alreadyList.stream()
.filter(var -> getNumber(var) == num)
.collect(Collectors.toList());
Will already throw the NullPointerException
in case getNumber(var)
would fail. Your try-catch
does not do anything different.
Upvotes: 1
Reputation: 12819
Catching a NPE is bad practice. NPE is an unchecked exception. From the docs:
If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.
Instead why not add another filter to the stream:
List<String> List = alreadyList.stream()
.filter(e -> e!= null)
.filter(var -> getNumber(var) == num)
.collect(Collectors.toList());
Upvotes: 3
Reputation: 206
It is bad practice to catch NullPointerException. You can use Optional class to avoid it and do necessary action only if object is present. You can throw other exceptions from your getNumber() method without any problems
Upvotes: 2