I have this piece of code, where I want to return an element if present, otherwise null
List<String> myList = new ArrayList<>();
myList.add("Test");
myList.add("Example");
myList.add("Sth");
String str = myList.stream()
.filter(x -> x.equals("eee"))
.findFirst()
.orElseGet(null);
but I got an Exception in thread "main" java.lang.NullPointerException anyway
orElseGet
takes a supplier. You want to use orElse
:
.findFirst().orElse(null);
It doesn't make much sense to use a supplier to return null, but if you were to, it would look like:
.findFirst().orElseGet(() -> null); //if argument is null, you get the NPE
The JavaDocs of orElseGet
(thanks to bambam's comment for the addition) mention it:
Throws:
NullPointerException - if value is not present and other is null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With