Java 8 Stream – Convert List<List<String>> to List<String>

As title, we can use flatMap to convert it.

Java9Example1.java

package com.mkyong.test;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Java9Example1 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "2", "A", "B", "C1D2E3");
        
        List<List<String>> collect = numbers.stream()
                .map(x -> new Scanner(x).findAll("\\D+")
                        .map(m -> m.group())
                        .collect(Collectors.toList())
                )
                .collect(Collectors.toList());

        collect.forEach(x -> System.out.println(x));

    }

}

Output


[]
[]
[A]
[B]
[C, D, E]

Solution

Java9Example2.java

package com.mkyong.test;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Java9Example2 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "2", "A", "B", "C1D2E3");

        List<String> collect = numbers.stream()
                .map(x -> new Scanner(x).findAll("\\D+")
                        .map(m -> m.group())
                        .collect(Collectors.toList())
                )									 	// List<List<String>>
                .flatMap(List::stream)					// List<String>
                .collect(Collectors.toList());


        collect.forEach(x -> System.out.println(x));

    }

}

Output


A
B
C
D
E

References

7 comments on “Java 8 Stream – Convert List<List<String>> to List<String>

  1. I have a list of object . inside that list one more list of object . I required get one value of a variable as comma separated string i tried as below but i am getting error can help
    String comaSepString =outerList.stream()
    .collect(Collectors.toList()).stream().map(p->p.getMessage()).collect(Collectors.joining(“,”)) ;

    Reply
  2. Your comments that say List and List<String> should really say Stream and Stream<String>, I think. They only convert to List after the call to collect(…)

    Reply
    1. Ah, can’t get the formatting correct for the angle brackets to display, but I think the intention is clear…

      Reply
  3. I guess this example to Convert List to List . Can you update title?
    “Java 8 Stream – Convert List to List” ?

    Reply
    1. The title is correct, this convert List List String to List String. Btw, what make you think so?

      Reply
      1. I was confused with Input ( List numbers) List . You are correct .

        Reply

Leave a Comment

Your email address will not be published. Required fields are marked *