I'm a little worried every time, so I'll write it as a memorandum
All you have to do is remember the idea of returning an empty stream with orElse
Summary
Optional.ofNullable(arr)
.map(Arrays::stream).orElse(Stream.empty())
.forEach(System.out::println);
I want to stream an array that may be null.
Extended for statements, ʻArrays # stream, and
Stream # of` are not null safe.
But it is troublesome to check null every time.
When using a for statement
String[] arr = null;
for (String s : arr) { //Here NullPointerException
System.out.println(s);
}
When using Arrays
String[] arr = null;
Arrays.stream(arr) //Here NullPointerException
.forEach(System.out::println);
// Stream#of also internally Arrays#Seems to be using stream
Stream.of(arr) //Here NullPointerException
.forEach(System.out::println);
Stream # empty
returns an empty streamWhen using Optional
String[] arr = null;
Optional.ofNullable(arr) //Optional at this point<String[]>
.map(Arrays.stream) //Optional at this point<Stream<String>>
.orElse(Stream.empty()) //Stream at this point<String>,Stream the contents of the array
.forEach(System.out::println);
Recommended Posts