How to Check if All Values in a List are True in Java
Table of Contents
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:
JAVAList<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:
JAVAboolean 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:
JAVAList<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
:
JAVAList<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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Learn how to build a Slack Bot using Node.js