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

Published Nov 5, 2021

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?

Verify using contains()

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

boolean isAllTrue = !list.contains(false);

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);

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.

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

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)

More Java Articles