flatMap and Primitive Streams

flatMap: One to Many

map turns each element into exactly one element. flatMap turns each element into a stream of elements and flattens all of them into one stream. Use it for lists of lists, order → items, sentence → words.

map:      [order1, order2]  ─►  [[pen, book], [bag]]
flatMap:  [order1, order2]  ─►  [pen, book, bag]

Flattening Order Items

Example

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

public class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order(1, List.of(new Item("Pen", 20, 3), new Item("Notebook", 60, 2))),
                new Order(2, List.of(new Item("Bag", 899, 1))),
                new Order(3, List.of(new Item("Pen", 20, 5), new Item("Bottle", 250, 1))));

        List<String> allItemNames = orders.stream()
                .flatMap(o -> o.items().stream())
                .map(Item::name)
                .distinct()
                .toList();
        System.out.println("Items: " + allItemNames);

        int totalRevenue = orders.stream()
                .flatMap(o -> o.items().stream())
                .mapToInt(i -> i.price() * i.qty())
                .sum();
        System.out.println("Revenue: " + totalRevenue);

        List<String> words = Stream.of("learn java daily", "java is fun")
                .flatMap(line -> Arrays.stream(line.split(" ")))
                .toList();
        System.out.println("Words: " + words);
    }
}

record Item(String name, int price, int qty) {}
record Order(int id, List<Item> items) {}

Output

Items: [Pen, Notebook, Bag, Bottle]
Revenue: 1429
Words: [learn, java, daily, java, is, fun]

IntStream, LongStream, DoubleStream

Primitive streams avoid boxing and add numeric methods: sum(), average(), max(), summaryStatistics(). Convert with mapToInt, boxed() and mapToObj.

Example

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

public class Main {
    public static void main(String[] args) {
        System.out.println("Sum 1..100 = " + IntStream.rangeClosed(1, 100).sum());
        System.out.println("Average = " + IntStream.of(70, 85, 90).average().getAsDouble());
        System.out.println("Squares = " + IntStream.range(1, 6).map(n -> n * n).boxed().toList());
        System.out.println("Stars   = " + IntStream.range(1, 4).mapToObj("*"::repeat).toList());
        System.out.println(DoubleStream.of(1.5, 2.5, 3.0).summaryStatistics());
        long bigSum = LongStream.rangeClosed(1, 1_000_000).sum();
        System.out.println("Sum 1..1,000,000 = " + bigSum);
    }
}

Output

Sum 1..100 = 5050
Average = 81.66666666666667
Squares = [1, 4, 9, 16, 25]
Stars   = [*, **, ***]
DoubleSummaryStatistics{count=3, sum=7.000000, min=1.500000, average=2.333333, max=3.000000}
Sum 1..1,000,000 = 500000500000