Transform Stream using Stream.flatMap()

The flatMap() method can be used for combining a stream of streams to one stream of objects. In this post I will show how to use flatMap() by using several use cases.

Use Case 1

Suppose you have a list of orders and each order contains a list of items.

class Order{
	String orderId;
	ArrayList<Item> items = new ArrayList<Item>();
 
	// ... 
}
 
class Item{
	String itemId;
	String itemName;
 
	// ... 
}

If you want to get all items in all orders, you can use flatMap() to flat the stream of streams.

ArrayList<Order> orders = new ArrayList<Order>();
Stream<Item> itemStream = orders.stream().flatMap(order -> order.getItems().stream());

Use Case 2

If you want to get a stream of words, you can use the following code:

Path path = Paths.get("/tmp/foo");
Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8);
Stream<String> words = lines.flatMap(line -> Stream.of(line.split("\\W+"))); //Split by non-word characters

Each line in the file is converted to a stream of words first, and then all those streams are combined into one single stream.

Reference:
Java Doc of Stream.flatMap()

Leave a Comment