Java Stream Peek Example: Count and Peek Elements in a Stream

count() and peek() are two methods in Java 8 Stream API that can be used to process data.

count() is a terminal operation that returns the count of elements in the stream. It is useful when we need to know the number of elements in a stream.

peek() is an intermediate operation that allows us to perform an action on each element of the stream as they are consumed. It is useful for debugging purposes, where we want to see the elements as they flow past a certain point in a pipeline.

Here’s an example of how to use count() and peek() together:

package the.basic.tech.info;

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

public class StreamExample {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("Java8", "StreamAPI", null, "Test", null);
		// count
		long c1 = list.stream().filter(str -> str != null).count();
		System.out.println("Count :" + c1);

		// peek
		list.stream().filter(str -> str != null) // Java8, StreamAPI, Test
				.peek(e -> System.out.println("Debug value: " + e)) // The peek method is used mainly for debugging.
				.collect(Collectors.toList());

	}

}

Output
Count :3
Debug value: Java8
Debug value: StreamAPI
Debug value: Test