I've just started dealing with Java 8 and have some questions regarding classes design. The one relates to Optional. The main ideas are to avoid NPE / return intelligible value in case of null. Frankly I don't understand why the following is possible:
List<String> innerListA = Arrays.asList(null, "B", "C");
String result= innerListA.stream().findFirst().orElse("mock");
Last line leads to NPE in findFirst()
. I understand that Optional doesn't garantee absence NPE in any possible case. But what is advantage of Optional in such simple case? If I understand correctly such a methods like findFirst()
/ findAny()
aim to retrieve Optonal object in stream. But in its turn it doesn't garantee absense of NPE. What is the point to apply orElse()
(that implies to return predictable value instead of nul) to the method that throws NPE?
I may be wrong so if anyone can explain such strange behavior please leave a comment.