Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Lists return element or null

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

like image 229
Nunyet de Can Calçada Avatar asked Dec 22 '18 07:12

Nunyet de Can Calçada


1 Answers

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

like image 91
ernest_k Avatar answered Oct 08 '22 22:10

ernest_k