## The challenge

Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

For example,

 ``````1 2 3 4 5 6 `````` ``````[true, true, true, false, true, true, true, true , true, false, true, false, true, false, false, true , true, true, true, true , false, false, true, true] ``````

The correct answer would be 17.

Hint: Don’t forget to check for bad values like `null`/`undefined`

## The solution in Java

In this code we will use Java’s `stream` functionality to move through each array element.

For each item we can make use of the `filter` functional and match for anything that is not `null` and that is `true`, then we return the `count` of all items that matched.

 ``````1 2 3 4 5 6 7 8 9 `````` ``````import java.util.*; public class Counter { public int countSheeps(Boolean[] arrayOfSheeps) { return (int)Arrays.stream(arrayOfSheeps) .filter(c -> c!=null && c==true) .count(); } } ``````

Another option may be to simply loop through the array in the traditional way:

 ``````1 2 3 4 5 6 7 `````` ``````public class Counter { public int countSheeps(Boolean[] arrayOfSheeps) { int count = 0; for (Boolean b : arrayOfSheeps) if (b) count++; return count; } } ``````

Or simply to use the `stream` technique from before, but instead of checking both `null` and `true` types, rather just check for valid boolean types:

 ``````1 2 3 4 5 6 7 `````` ``````import java.util.Arrays; public class Counter { public int countSheeps(Boolean[] arrayOfSheeps) { return (int) Arrays.stream(arrayOfSheeps).filter(Boolean::booleanValue).count(); } } ``````

## Test cases to validate our code

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 `````` ``````import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class CounterTest { static Boolean[] array1 = {true, true, true, false, true, true, true, true , true, false, true, false, true, false, false, true , true, true, true, true , false, false, true, true }; static Boolean[] array2 = new Boolean[605]; static Boolean[] array3 = new Boolean[605]; static { int index = 0; for (; index < 500; index++) array2[index] = true; for (; index < 5; index++) array2[index] = null; for (; index < 100; index++) array2[index] = false; index = 0; for (; index < 505; index++) array3[index] = null; for (; index < 100; index++) array3[index] = false; } @Test public void test1() { assertEquals("There are 17 sheeps in total", 17, new Counter().countSheeps(array1)); } @Test public void test2() { assertEquals("There are 500 sheeps in total", 500, new Counter().countSheeps(array2)); } @Test public void test3() { assertEquals("There are 0 sheeps in total", 0, new Counter().countSheeps(array3)); } } ``````