转换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 Stream
s:
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]