Skip to content
Advertisement

stream filter return null findFirst getting exception

The following will throw an exception, if the personList is empty or the filtered result is empty:

Person b2cInwardAllocTxs = personList.stream()
   .filter(x -> x.getName().equalsIgnoreCase("Alvin"))
   .findFirst().get();

I get the following error:

Exception: java.util.NoSuchElementException: No value present

How to solve the error?

Actually, I just expect it should return one object or null.

Advertisement

Answer

get will throw an exception if called on an empty Optional. Instead, you could use orElse to return a null:

Person b2cInwardAllocTxs = 
    personList.stream()
              .filter(x -> x.getName().equalsIgnoreCase("Alvin"))
              .findFirst()
              .orElse(null);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement