How to Check if All Values in a List are True in Java

Updated onbyAlan Morel
How to Check if All Values in a List are True in Java

Lists in Java are useful because you can store a collection of items and then perform operations on all of them.

If you have a list of values that evaluate to a boolean, it might be useful to know if they are all true or not.

In this post, we'll learn how to check if all values in a list are true in Java.

Check if all values in a list are true

First, let's start out with an example list of three true booleans:

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

The first way to check if they are all true is to use the contains method, which returns true if the list contains the specified element:

JAVA
boolean allTrue = !booleans.contains(false);

If any element contains a false, this will return true, but then we negate it with the ! operator to get the correct result.

Another way to check this is to take advantage of the facts that sets only allow unique values.

Because of this feature, we can just dump the entire list into a set, and we will be left with only true, false, or both. From there, we do a contains check like before:

JAVA
List<Boolean> booleans = Arrays.asList(true, true, true); Set<Boolean> set = new HashSet<>(booleans); boolean allTrue = !set.contains(true);

The final way we can make this check is to take advantage of the more modern Stream API. All we need to do is create a stream from the list and check that they are all true:

JAVA
List<Boolean> booleans = Arrays.asList(true, true, true); boolean allTrue = booleans.stream().allMatch(b -> b);

Conclusion

In this post, we learned how to check if all values in a list are true in Java.

We saw three different ways to do this, and each one has its own advantages and disadvantages.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.