Booleans utility example

This example will demonstrate various methods available in the Guava Boolean static utility.

Array contains

Passing in an array Booleans.contains will return true if any element in the primitive boolean array contains the target or in this case true.

public void boolean_array_contains () {

    boolean[] booleanArray = {true, false, true, false};

    boolean arrayContains = Booleans.contains(booleanArray, true);


Find index of element

Calling the Booleans.indexOf will return the first occurrence of value target, false, in the array.

public void boolean_array_index () {

    boolean[] booleanArray = {true, false, true, false};

    int index = Booleans.indexOf(booleanArray, false);

    assertEquals(1, index);

Combine two boolean arrays

This snippet will concatenate two boolean arrays together by calling Booleans.concat.

public void concat_boolean_arrays () {

    boolean[] booleanArray1 = {true, false};
    boolean[] booleanArray2 = {true, false};

    boolean[] concatedArray = Booleans.concat(booleanArray1, booleanArray2);

    assertEquals(4, concatedArray.length);

Convert primitive array to list

This snippet will convert a primitive array to ArrayList of Booleans.

public void convert_boolean_array_to_Boolean_list () {

    boolean[] booleanArray = {true, false, true, false};

    List<Boolean> booleans = Booleans.asList(booleanArray);

    assertEquals(4, booleans.size());

Convert list to primitive array

This snippet will convert an ArrayList of Booleans to a primitive boolean array.

public void convert_Boolean_to_primitive () {

    List<Boolean> booleans = Lists.newArrayList(
            Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE);

    boolean[] primitiveArray = Booleans.toArray(booleans);

    assertEquals(4, primitiveArray.length);

Count number of booleans

Similar to behavior demonstrated in count occurrence of booleans in arraylist, this snippet will use Booleans.countTrue to return the number of true values contained in the array.

public void count_total_number_of_booleans () {

    boolean [] values = {true, true, false, true, false};

    int count = Booleans.countTrue(values);

    assertEquals(3, count);

Join array elements as string

This snippet will join array elements with a delimiter by calling Booleans.join.

public void join_elements_of_boolean_array () {

    boolean[] booleanArray = {true, false, true, false};

    String joinedElements = Booleans.join("-", booleanArray);

    assertEquals("true-false-true-false", joinedElements);