Java 8 – Returning an empty Optional

  • A+
Category:Languages

I have this method that I want to return an empty optional is nothing is found

@Override public Optional<Menu> findBySymbol (String symbol) {     Optional<Menu> menu =                      StreamSupport                     .stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)                     .findFirst();      return menu.orElse(Optional.empty());  } 

but I got a compilation error: Type mismatch: cannot convert from Optional<Object> to Menu

 


why not just return it?

return StreamSupport.stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)                      .findFirst(); 

Comment

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