Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Intermediate Processing with the peek() Method | Проміжні Операції у Stream API
Stream API

Intermediate Processing with the peek() Method

Свайпніть щоб показати меню

Note
Definition

In the Java Stream API, the peek() method is used for intermediate processing of stream elements, typically for debugging or performing actions on each element without modifying the stream itself.

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.

Stream<T> peek(Consumer<? super T> action);

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.java

Main.java

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?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 11

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 2. Розділ 11
some-alt