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,
[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.
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:
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:
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
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));
}
}