Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: reduce vs anyMatch vs contains

 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?

like image 401
ealeon Avatar asked Apr 05 '19 00:04

ealeon


People also ask

What is the difference between the anyMatch () and findAny () stream methods?

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.

Is anyMatch a terminal operation?

The anyMatch method is a short-circuiting terminal operation.

What is stream () in Java?

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.

How do you check if a value is present in a List in Java 8?

We can check whether an element exists in ArrayList in java in two ways: Using contains() method. Using indexOf() method.


1 Answers

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);
like image 72
Misha Avatar answered Sep 22 '22 12:09

Misha