Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Intermediate Processing with the peek() Method | Intermediate Operations in Stream API
Stream API
course content

Course Content

Stream API

Stream API

1. Fundamentals and Functional Capabilities of Stream API
4. Practical Applications of Stream API

book
Intermediate Processing with the peek() Method

The peek() method allows us to insert logging at the processing stage without altering the data stream, and then proceed with operations on elements that pass the necessary filtering.

This method accepts an object implementing the Consumer interface, which performs an operation on each stream element.

Practical Example

A factory needs to inspect products to ensure their names start with "product-" and match a specific pattern. At the same time, you want to log all products in the list. Valid products should be collected into a list and printed to the console.

java

Main

copy
123456789101112131415161718192021
package com.example; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<String> items = Arrays.asList("product-H31KD", "product-A12ZX", "item-X99KD", "product-B67QF", "product-12345", "invalidData"); // Example of using peek for logging and collecting filtered elements into a new list List<String> validProducts = items.stream() .peek(item -> System.out.println("Checking item: " + item)) .filter(item -> item.startsWith("product-")) .toList(); // Collecting filtered elements into a list // Printing the list of validated products System.out.println("List of validated products: " + validProducts); } }

The code filters elements from the items list, keeping only those that start with "product-". The peek() method logs each checked element, and the valid products are collected into a list and printed to the console.

question mark

What does the peek() method do in the Stream API?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 11
We're sorry to hear that something went wrong. What happened?
some-alt