をコーディングするビット近いです。
メソッドシグネチャをallTrue(Iterable<Boolean> booleans)
に変更する場合は、ブール値配列をトラバースする特別なIterator<Boolean>
を作成するだけです。
import java.util.Iterator;
import java.util.NoSuchElementException;
public class BooleanAllTrue {
public static boolean allTrue(Iterable<Boolean> booleans) {
if (booleans == null) return false;
for (Boolean bool : booleans) {
if (!bool) return false;
}
return true;
}
public static Iterable<Boolean> asIterable(final boolean[] booleens) {
return new Iterable<Boolean>() {
public Iterator<Boolean> iterator() {
final boolean[] booleans = booleens;
return new Iterator<Boolean>() {
private int i = 0;
public boolean hasNext() {
return i < booleans.length;
}
public Boolean next() {
if (!hasNext()) throw new NoSuchElementException();
return booleans[i++];
}
public void remove() {throw new UnsupportedOperationException("remove");}
};
}
};
}
public static void main(String [] args) {
System.out.println(allTrue(asIterable(new boolean[]{true, true})));
System.out.println(allTrue(asIterable(new boolean[]{true, false})));
try {
asIterable(new boolean[0]).iterator().next();
} catch (NoSuchElementException e) {
// expected
}
}
}
最後に、allTrue(boolean[] booleans)
の方法。
public static boolean allTrue(boolean[] booleans) {
return allTrue(asIterable(booleans));
}
万が一あなたはグアバを使用していますか? – shmosel
http://stackoverflow.com/a/5606435/2310289 –
@shmosel No Guava – Kwoppy