Convert Delimited String in List<String> to List<String>

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 Streams:

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]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23200&siteId=1