I have two functions which check if all elements of an array or list are true
. I'm having trouble combining the two. How can I make the functions into one generic Java function.
public static boolean allTrue(boolean[] booleans) {
if (booleans == null) {
return false;
}
for (boolean bool : booleans) {
if (!bool) {
return false;
}
}
return true;
}
public static boolean allTrue(List<Boolean> booleans) {
if (booleans == null) {
return false;
}
for (boolean bool : booleans) {
if (!bool) {
return false;
}
}
return true;
}
If you're using Guava, you can wrap the boolean array in Booleans.asList()
and pass it as a list:
public static boolean allTrue(boolean[] booleans) {
return booleans != null && allTrue(Booleans.asList(booleans));
}
As per https://stackoverflow.com/a/5606435/2310289
You could just accept an Object
public static boolean allTrue(Object booleans) {
and then check for instanceof boolean[]
or instanceof List<Boolean>
and then perform different code within the method.
Again, not really an improvement, but a bit closer to code unification
I think the answer given by @Joel was a good one, except for the issue pointed out in the comment. If we just convert boolean[]
to Boolean[]
, we can try the following:
public static boolean allTrue(List<Boolean> booleans) {
if (booleans == null) {
return false;
}
for (boolean bool : booleans) {
if (!bool) {
return false;
}
}
return true;
}
public static boolean allTrue(boolean[] booleans) {
Boolean[] newArray = new Boolean[booleans.length];
int i = 0;
for (boolean value : booleans) {
newArray[i++] = Boolean.valueOf(value);
}
return Arrays.asList(newArray);
}
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