Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to python all and any

Tags:

java

python

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...

like image 254
Hyperboreus Avatar asked Sep 22 '13 04:09

Hyperboreus


People also ask

Is there an any in Java?

Class Any. Serves as a container for any data that can be described in IDL or for any IDL primitive type. An Any object is used as a component of a NamedValue object, which provides information about arguments or return values in requests, and which is used to define name/value pairs in Context objects.

Does Java have list like Python?

Java has an interface called list, which has implementations such as ArrayList, AbstractList, AttributeList, etc.

Is there a Java equivalent to with?

try-with-resources is its Java equivalent, and is available in Java 7 and up. This is the try-with-resources construct.

Is there a pass statement in Java?

Java is always a pass by value; but, there are a few ways to achieve pass by reference: Making a public member variable in a class. Return a value and update it. Create a single element array.


2 Answers

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().

like image 91
Matt Ball Avatar answered Sep 17 '22 16:09

Matt Ball


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 ...)

like image 37
Stephen C Avatar answered Sep 17 '22 16:09

Stephen C