Learnitweb

Stream peek() Method in Java

1. Introduction

The syntax of peek method is:

Stream<T> peek(Consumer<? super T> action)
  • This method returns a stream consisting of the elements of this stream. This method accepts a Consumer as an argument, so it performs action defined by the Consumer on each element.
  • The peek method in Stream is a very useful way to look at the stream elements. This method is commonly used for debugging purpose.
  • This is an intermediate operation. Using peek without any terminal operation does nothing. So there must be a terminal operation to see the affect of processing.
  • For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation.

2. peek method without terminal operation

peek() is an intermediate operation and does nothing unless terminal method is called.

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class Test {
	public static void main(String[] args) throws IOException {
		List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

		list.stream().peek(System.out::println); // prints nothing
	}
}

3. peek method with terminal operation

peek() method needs a terminal operation to start the processing.

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

public class Test {
	public static void main(String[] args) throws IOException {
		List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

		List<Integer> newList = list.stream().peek(System.out::println).collect(Collectors.toList());

		System.out.println(newList);
	}
}

Output

1
2
3
4
5
[1, 2, 3, 4, 5]