Java8 Lists return element or null

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: