Java Optional: Handling Null Values Without Using If Statements
You can use the 'Optional' class to check for null values and handle them without using an 'if' statement. Here's an example:
return Stream.of(LocalAndMunicipalCompanyEnum.values())
.filter(predicate)
.findFirst()
.map(mapper)
.orElseGet(() -> value);
In this code, the 'orElseGet' method is used to provide a fallback value ('value') if the 'Optional' is empty. The lambda expression '() -> value' is used to create a supplier that returns the fallback value. This ensures that the fallback value is only evaluated if necessary.
原文地址: https://www.cveoy.top/t/topic/p3PY 著作权归作者所有。请勿转载和采集!