# flatMap() method

In 
Published 2023-06-10

This tutorial explains how we can use flatMap() method for Streams in Java.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

From the base application downloaded from Spring Initializr, I updated the main class as below:

DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) throws InterruptedException, ExecutionException {

		// Create the application context and start Spring Boot
		ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);

		List<List<String>> wordsList = Arrays.asList(
				Arrays.asList("John", "Dan Brown"),
				Arrays.asList("Laptop", "BMW", "Laptop"),
				Arrays.asList("computer", "project"));

		wordsList.stream()
				// Stream<List<String>> will be converted to Stream<String>
				.flatMap(Collection::stream)
				.forEach(p -> System.out.println(p));
	}
}

When I run this code I receive:

John
Dan Brown
Laptop
BMW
Laptop
computer
project