List<Boolean> results = new ArrayList<>();
results.add(true);
results.add(true);
results.add(true);
results.add(false);
if (results.contains(false)) {
System.out.println(false);
} else {
System.out.println(true);
}
System.out.println(results.stream().reduce((a, b) -> a && b).get());
//System.out.println(!results.stream().anyMatch(a -> a == false));
System.out.println(!results.stream().anyMatch(a -> !a));
OUTPUT:
false
false
false
FYI, the results are a result of a map+collect op
List<Job> jobs;
List<Boolean> results = job.stream().map(j -> j.ready()).collect(Collector.toList())
If I choose either reduce or anyMatch, I don't have to collect the results from map operation.
From results which is a list of boolean, I just want to return false if there is at least one false.
I can do it via reduce or anyMatch. I kinda don't like Optional from reduce, and I kinda don't like that I have to negate anyMatch
Are there any pros/cons for using either?
They do the same job internally, but their return value is different. Stream#anyMatch() returns a boolean while Stream#findAny() returns an object which matches the predicate.
The anyMatch method is a short-circuiting terminal operation.
A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.
We can check whether an element exists in ArrayList in java in two ways: Using contains() method. Using indexOf() method.
It appears that the only reason you are collecting the booleans into the list is so you can check if some are false
:
If I choose either reduce or anyMatch, I don't have to collect the results from map operation [...] I just want to return false if there is at least one false.
If this is the case, then you definitely should consider the straightforward stream-based approach:
return jobs.stream().allMatch(Job::ready);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With