lambda - What's the right way to check null or check exceptions in a chained statement in Java 8? -
for example code:
list<class> classes = stream.of("java.lang.object", "java.lang.integer", "java.lang.string") .map(classname -> class.forname(classname)) .collect(collectors.tolist()); this code runs fine now. but, assume have empty list in stream , have tons of operations stream. nullpointer exceptions , etc. find it's hard try-catch kind of statement. what's right way handle exception this?
you not need check nulls. if have empty stream operations skipped:
stream.of("hello") .filter(e => "world".equals(e)) // empties stream .foreach(system.out::println); // no nullpointer, no output exception handling 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 want exceptions ignored, suggest map optionals.
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 have @ how can throw checked exceptions inside java 8 streams? more detailed discussion class.forname in combination java 8 streams.
Comments
Post a Comment