Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make function generic for List<Boolean> and boolean[]

Tags:

java

generics

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;
}
like image 534
Kwoppy Avatar asked Feb 10 '17 02:02

Kwoppy


3 Answers

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));
}
like image 104
shmosel Avatar answered Oct 18 '22 10:10

shmosel


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

like image 30
Scary Wombat Avatar answered Oct 18 '22 11:10

Scary Wombat


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);
}
like image 20
Tim Biegeleisen Avatar answered Oct 18 '22 09:10

Tim Biegeleisen