Hyperboreus
Hyperboreus

Reputation: 32459

Java equivalent to python all and any

How do I code in Java the following python lines?

a = [True, False]
any (a)
all (a)

inb4 "What have you tried?"

The sledge-hammer way would be writing my own all and any methods (and obviously a class to host them):

public boolean any (boolean [] items)
{
    for (boolean item: items)
        if (item) return true;
    return false;
}

//other way round for all

But I don't plan on re-inventing the wheel and there must be a neat way to do this...

Upvotes: 19

Views: 19398

Answers (3)

Matt Ball
Matt Ball

Reputation: 360056

any() is the same thing as Collection#contains(), which is part of the standard library, and is in fact an instance method of all Collection implementations.

There is no built-in all(), however. The closest you'll get, aside from your "sledgehammer" approach, is Google Guava's Iterables#all().

Upvotes: 13

Cwt
Cwt

Reputation: 8606

An example for Java 8 streaming API would be:

Boolean[] items = ...;
List<Boolean> itemsList = Arrays.asList(items);
if (itemsList.stream().allMatch(e -> e)) {
    // all
}
if (itemsList.stream().anyMatch(e -> e)) {
    // any
}

A solution with the third party library hamcrest:

import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;

if (everyItem(is(true)).matches(itemsList)) {
    // all
}
if (hasItem(is(true)).matches(itemsList)) { // here is() can be omitted
    // any
}

Upvotes: 10

Stephen C
Stephen C

Reputation: 719709

In Java 7 and earlier, there is nothing in the standard libraries for doing that.

In Java 8, you should be able to use Stream.allMatch(...) or Stream.anyMatch(...) for this kind of thing, though I'm not sure that this would be justifiable from a performance perspective. (For a start, you would need to use Boolean instead of boolean ...)

Upvotes: 11

Related Questions