Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream return property or null

Tags:

java

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();
like image 251
CaptRespect Avatar asked Mar 07 '23 12:03

CaptRespect


1 Answers

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:

  • First, we filter the list of properties using a Stream in order to keep only the properties with the given id with the method filter. This transforms a Stream to a Stream;
  • Then, we get the bean property with a 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());
  • Finally, we call 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.

like image 91
D. Lawrence Avatar answered Mar 15 '23 02:03

D. Lawrence