Debugging Java 8 Streams

The peek() method is useful for debugging Java 8 stream(s).

This example doesn’t need an explicit peek(), but it shows how useful the peek method is for debugging:

package com.chocksaway;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Author milesd on 31/12/2017.
 */
public class FilterNumbers {
    private List<Integer> numberList;

    public FilterNumbers(List<Integer> numberList) {
        this.numberList = numberList;
    }

    public List<Integer> process() {
        return numberList.stream()
            .filter(each -> each > 15)

            // peek for the first filter
            .peek(each -> System.out.println("Debug 001:\t " + each))

            .filter(each -> each % 3 == 0)

            // peek for the second filter
            .peek(each -> System.out.println("Debug 002:\t " + each))

            .collect(Collectors.toList());
    }
}
Corresponding Unit Test:
import com.chocksaway.FilterNumbers;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static junit.framework.TestCase.assertTrue;

/**
 * Author milesd on 31/12/2017.
 */
public class TestFilterNumbers {
    @Test
    public void peekAtLambda() {
        List<Integer> numbers = new ArrayList<>(List.of(12, 13, 14, 15, 20, 21, 24));
        FilterNumbers filterGreaterFifteenDivisibleByThree = new FilterNumbers(numbers);

        List<Integer> result = filterGreaterFifteenDivisibleByThree.process();

        assertTrue(result.contains(21));
        assertTrue(result.contains(24));
    }
}
Running the Unit Test

The debug output:

Debug 001:	 20
Debug 001:	 21
Debug 002:	 21
Debug 001:	 24
Debug 002:	 24

peek() shows the Debug 001, and Debug 002 for the first and second filter second statements.

Author | Miles Davenport

Career programmer, who designs, assembles, fixes, and supports customers, software and systems.