FlatMap Flattens And Builds Pairs

flatMap expands each stream element into a sub-stream, generating ordered pair combinations or flattening nested lists in one pipeline.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.stream.Collectors;

public class PairGrid {

    public static void main(String[] args) {
        List<String> drinks = List.of("tea", "coffee");
        List<String> sizes = List.of("S", "L");

        // flatMap 把每个元素展开成子流:两层嵌套生成有序对
        List<String> combos = drinks.stream()
                .flatMap(d -> sizes.stream().map(s -> d + "-" + s))
                .collect(Collectors.toList());
        System.out.println(combos);

        // 打平嵌套列表同样适用:空子列表直接消失
        List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of());
        List<Integer> flat = nested.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
        System.out.println(flat);
    }
}

The flow from top to bottom

FlatMap Flattens And Builds Pairs is built around the class PairGrid and the function main.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Points of care

  • A package manager never enters the picture — each call resolves to a built-in API.

Putting it to use

The entry-point signature is public static void main(String[] args)

Core lines

.collect(Collectors.toList());

FAQ

How do you run FlatMap Flattens And Builds Pairs?
The runtime alone is enough: execute the file as a complete program.