Sobes.tech
Senior

How to output numbers and build a Map in one stream?

sobes.tech AI

Answer from AI

In Java Stream API, you can simultaneously output elements and build a Map in a single pass by using the peek method for output and the terminal collect method for collecting into a Map. For example:

import java.util.*;
import java.util.stream.*;

public class Example {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("one", "two", "three");

        Map<String, Integer> map = list.stream()
            .peek(s -> System.out.println("Element: " + s)) // output element
            .collect(Collectors.toMap(
                s -> s,          // key — the element itself
                String::length   // value — length of the string
            ));

        System.out.println("Map: " + map);
    }
}

Here, peek allows performing a side effect (printing to the console) without interrupting the stream, and collect gathers the elements into a Map. Thus, output and Map construction happen in a single stream.