You do not need to check for nulls. If you have an empty stream all operations will be skipped:
Stream.of("hello")
.filter(e => "world".equals(e)) // empties the stream
.foreach(System.out::println); // no NullPointer, no output
Exception handling is possible in mapper:
List<Class<?>> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(className -> {
try {
return Class.forName(className);
} catch (Exception e) {
throw new YourRuntimeException();
}
})
.collect(Collectors.toList());
If you want exceptions to be ignored, then I suggest to map to Optional
s.
List<Class<?>> classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(className -> {
try {
return Optional.of(Class.forName(className));
} catch (Exception e) {
return Optional.<Class<?>>empty();
}
})
.filter(Optional::isPresent) // ignore empty values
.map (Optional::get) // unwrap Optional contents
.collect(Collectors.toList());
Please also have a look at How can I throw CHECKED exceptions from inside Java 8 streams? for a more detailed discussion about Class.forName
in combination with java 8 streams.