return optionalPlayer.orElseThrow(() -> new PlayerNotFoundException(name)); } }
We could write the same function, but this time we return the FootballPlayer object if it is found, and if not, we throw an exception. This really improves the code and makes it more readable, as we leverage also the benefits of the Stream class.
However, sometimes you want to return a default object if the one that you are looking for cannot be found. There are two ways you can do it.
return optionalPlayer.orElseGet(() -> new FootballPlayer("Neymar Jr.", 29)); } }
Difference
The difference between the two is that despite of the condition that optionalPlayer is null or not, the object inside orElse will always be created. In fact, it is created before the conditon is evaluated. However, this is not the case for orElseGet . The object is created only if the optionalPlayeris null.