Java Stream How to - Use flatMap








Question

We would like to know how to use flatMap.

Answer

import java.util.Arrays;
import java.util.List;
//from w  w  w.ja  va 2s .c  o m
public class Main {

  public static void main(String[] args) throws Exception{
    // map
    List<String> words = Arrays.asList("Hello", "World");

    words.stream()
    .flatMap((String line) -> Arrays.stream(line.split("")))
    .distinct()
    .forEach(System.out::println);

  }

}

The code above generates the following result.