Java 8 Stream Convert List<List<String>> to List<String>
By:Roy.LiuLast updated:2019-08-11
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
From:一号门
Previous:Java Regular Expression Examples
COMMENTS