How to Check If All Values in List are True in Java


Suppose we have a boolean list in Java that might look something like this.

List<Boolean> list = Arrays.asList(true, true);

How can we verify that this list contains only true values?

1. Verify using contains()

We can simply use the contains() method to check for values in a list.

boolean isAllTrue = !list.contains(false);

2. Verify using a Set

If we’re going to make this check many times, it might be helpful to use a set instead.

Set<Boolean> set = new HashSet<Boolean>(list);
boolean isAllTrue = !set.contains(false);

3. Verify using Stream API

In Java 8, we can use the stream() and allMatch() to get the same functionality.

boolean isAllTrue = list.stream().allMatch(n -> n == true);

A more concise solution might include Boolean::valueOf or Boolean.TRUE::equals.

boolean isAllTrue = list.stream().allMatch(Boolean::valueOf);
boolean isAllTrue = list.stream().allMatch(Boolean.TRUE::equals);

4. Either all true or all false

We can also check if a list is entirely true or entirely false using the Stream API and Boolean::booleanValue.

boolean isAllTrueOrAllFalse = list.stream().allMatch(Boolean::booleanValue)