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;
}
}
getNumbermethod throwsNullpointerexceptionand 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());
NullPointerExceptionis an unchecked exception and so you don't need to catch / throw it explicitly at all (and arguably shouldn't.) So the short answer is the stream based code you have is already the equivalent of what's above, the code above just has some needless exception catching in it.