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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
2 Comment threads
4 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
MOHAMMED EL AMINE MOUFOKJamesmkyongsrinivas Recent comment authors
newest oldest most voted
James
Guest
James

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(…)

James
Guest
James

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

srinivas
Guest
srinivas

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