Why does this throw a java.lang.NullPointerException
?
List<String> strings = new ArrayList<>();
strings.add(null);
strings.add("test");
String firstString = strings.stream()
.findFirst() // Exception thrown here
.orElse("StringWhenListIsEmpty");
//.orElse(null); // Changing the `orElse()` to avoid ambiguity
The first item in strings
is null
, which is a perfectly acceptable value. Furthermore, findFirst()
returns an Optional, which makes even more sense for findFirst()
to be able to handle null
s.
EDIT: updated the orElse()
to be less ambiguous.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…