Course Content
Stream API
Stream API
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.
Main
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.
Thanks for your feedback!