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...
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.
Java has an interface called list, which has implementations such as ArrayList, AbstractList, AttributeList, etc.
try-with-resources is its Java equivalent, and is available in Java 7 and up. This is the try-with-resources construct.
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.
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()
.
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
...)
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