Roger Ng :
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 ,
?
Input: [ "1,2", "3,4", "5" ]
Output: [ "1", "2", "3", "4", "5" ]
Imperative code
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);
}
}
Eran :
You can do it with Stream
s:
List<String> output = input.stream()
.flatMap(s -> Arrays.stream(s.split(",")))
.collect(Collectors.toList());
For example,
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);
will output
[1, 2, 3, 4, 5]