Main Tutorials

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 Author

author image
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

Subscribe
Notify of
7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Tonny
4 years ago

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(“,”)) ;

James
4 years ago

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
4 years ago
Reply to  James

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

srinivas
4 years ago

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

MOHAMMED EL AMINE MOUFOK
4 years ago
Reply to  mkyong

good job

srinivas
4 years ago
Reply to  mkyong

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