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 | Intermediate Operations in Stream API
Introduction to Stream API

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

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

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  11

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  11
some-alt