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

摘要: As title, we can use flatMap to convert it.

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



上一篇: Java Regular Expression Examples
下一篇: How to loop an enum in Java
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号