Welcome to our in-depth guide on the peek() method in Java Stream API! By the end of this lesson, you'll have a solid understanding of how to use this powerful tool to inspect elements during a stream pipeline. Let's dive in! šÆ
The peek() method in Java Stream API is a useful utility for inspecting elements during the processing of a stream pipeline without affecting the result. It allows you to see the elements as they flow through the pipeline, making it easier to debug and understand the sequence of operations.
Let's start with a simple example. Suppose we have a list of integers and we want to find the sum of all even numbers:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
int sum = numbers.stream()
.filter(n -> n % 2 == 0) // Filter out odd numbers
.peek(n -> System.out.println("Peek: " + n)) // Print each even number
.mapToInt(Integer::intValue)
.sum();In this example, we use peek() to print each even number as they are processed by the stream pipeline. The final result (sum of all even numbers) is the same as if we didn't use peek().
š Note: The peek() method doesn't modify the original source, so it's safe to use it for debugging purposes without affecting the final result.
Sometimes, you may want to perform a more complex action when peeking at an element. For this, you can create a custom Consumer object and pass it to the peek() method.
import java.util.function.Consumer;
// Define a custom consumer that prints the square of the number
Consumer<Integer> squarePrinter = n -> System.out.println("Peek: " + (n * n));
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.peek(squarePrinter) // Print the square of each even number
.mapToInt(Integer::intValue)
.sum();In this example, we created a custom Consumer object called squarePrinter that squares the number when it's peeked. You can customize this object to perform any action you need while inspecting elements during the stream pipeline.
That's all for our Java Stream peek() tutorial! We hope you found this lesson helpful in understanding how to use the peek() method to inspect elements during a stream pipeline and debug your code more effectively. Happy coding! š