Java 8 (LTS) · Topic 7 of 12
flatMap
Definition​
flatMap turns each item into a stream and joins all of those streams into one. Use it when each item holds a list and you want one flat list of everything.
Example code​
From a list of orders to one list of items
import java.util.List;
record Order(int id, List<String> items) { }
class Demo {
public static void main(String[] args) {
List<Order> orders = List.of(
new Order(1, List.of("book", "pen")),
new Order(2, List.of("lamp")),
new Order(3, List.of("pen", "bag")));
List<String> allItems = orders.stream()
.flatMap(order -> order.items().stream()) // many lists become one stream
.distinct()
.toList();
System.out.println(allItems);
}
}
// Output:
// [book, pen, lamp, bag]
Finished this page? Track your progress (saved only in your browser).