Q:

Check parameters of method with 6 input Boolean parameters

I have the following method:
public boolean my_method(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6){ 
// ... 
}

I got asked to write the code so that this method returns true only if two and only two of the parameters list is true.
I'm not sure about the best practice for that. I appreciate your suggestions.
Thanks!

A:

I am always a fan of the stream API, so here's one solution:
public boolean method(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6) {
    Boolean[] array = { b1, b2, b3, b4, b5, b6 };
    return Arrays.stream(array).filter(x -> x).count() == 2;
}

First, I put all the parameters into an array. Then I filtered all the items that are true and counted them. Finally return whether that count is equal to 2.
Although the above very little code to write, it boxes the booleans into Booleans. If you don't like boxing, try this:
public boolean method(boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6) {
    boolean[] array = { b1, b2, b3, b4, b5, b6 };
    int count = 0;
    for (boolean item: array) {
        if (item) {
            count++;
        }
    }
    return count == 2;
}

This is pretty straightforward, no need to explain.

