Ram Viswanathan
Ram Viswanathan

Reputation: 201

Iterate list look for boolean attribute, return default false

I have a list of objects, each object has a boolean attribute. For example,

public class A {
   private boolean isAvailable;
}

I would like to iterate this list, get the value of "isavailable" of the first element in the list. If the list is empty or null, then I would like to return false.

Can I do this efficiently with Java8 streams?

Upvotes: 0

Views: 750

Answers (1)

Samuel Philipp
Samuel Philipp

Reputation: 11040

Of course that is possible with Java Streams:

boolean result = list.stream().findFirst().map(A::isAvailable).orElse(false);

Use the findFirst() method to get the first value of the list if present. Map isAvailable and return false if the list is empty.

I would strongly discourage using null as list value. Use an empty list instead.

But if you want to do so you can use an Optional to wrap the list:

boolean result = Optional.ofNullable(list)
        .flatMap(l -> l.stream().findFirst().map(A::isAvailable))
        .orElse(false);

Upvotes: 1

Related Questions