转换List< String>中的定界字符串列出< String> [英] Convert Delimited String in List<String> to List<String>

查看:66
本文介绍了转换List< String>中的定界字符串列出< String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个List<String>,其中某些值包含定界符,,我们如何将split合并为List<String>而没有定界符,?

Assume we have a List<String> with some values containing the delimiter ,, how do we convert split and merge into a List<String> without the delimiter ,?

输入:[ "1,2", "3,4", "5" ]

输出:[ "1", "2", "3", "4", "5" ]

验证码

List<String> input = Arrays.asList("1,2", "3,4", "5");
List<String> output = new ArrayList<>();
for (String str : input) {
  for (String split : str.split(",")) {
    output.add(split);
  }
}

推荐答案

您可以使用Stream s来做到这一点:

You can do it with Streams:

List<String> output = input.stream()
                           .flatMap(s -> Arrays.stream(s.split(",")))
                           .collect(Collectors.toList());

例如,

List<String> input = Arrays.asList("1,2", "3,4", "5" );
List<String> output = input.stream()
                           .flatMap(s -> Arrays.stream(s.split(",")))
                           .collect(Collectors.toList());
System.out.println (output);

将输出

[1, 2, 3, 4, 5]

这篇关于转换List&lt; String&gt;中的定界字符串列出&lt; String&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆