Is there a way using streams to return the property of a bean or null if the bean isn't present?
Something like:
String property = beans.stream()
.filter(bean -> bean.getId() == id).findFirst().orElse(null).beanProperty();
First, Let's write some lines of code that we will then analyse.
The best way to achieve this is to do the following:
String property = beans.stream()
.filter(bean -> bean.getId() == id)
.findFirst()
.map(Property::beanProperty)
.orElse(null);
A bit of explanations is in order here:
Stream
in order to keep only the properties with the given id with the method filter
. This transforms a Stream
to a Stream
;map
. Please note that this method will apply the desired mapping function to the content of the Optional
if and only if the latter is not empty. Also note that I assumed we had a POJO called Property
for our properties and that I used a method reference to get the property. It would be equivalent to write .map(prop -> prop.beanProperty())
;orElse
of Optional
that is equivalent in either taking the content of the Optional if not empty or taking the value given in parameter, in our case null
.As a final word, please take care that the signature of the map
function is the following:
public<U> Optional<U> map(Function<? super T, ? extends U> mapper)
The latter is therefore applying the function on a Optional
and returning an Optional
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With