1

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);
  }
}
Roger Ng
  • 771
  • 11
  • 28
  • 1
    I think you may be looking for some flatMap – radrow Mar 04 '20 at 13:23
  • and what did you try? – Naman Mar 04 '20 at 13:26
  • Possible duplicate of [How to convert comma-separated String to ArrayList?](https://stackoverflow.com/questions/7488643/how-to-convert-comma-separated-string-to-arraylist) and then [How can I turn a List of Lists into a List in Java 8?](https://stackoverflow.com/questions/25147094/how-can-i-turn-a-list-of-lists-into-a-list-in-java-8) – Naman Mar 04 '20 at 13:26
  • @Naman The first question is pretty similar but not exactly answering this question as the `.flatMap()` is not mentioned in that question. The second one looks like a duplicate of this question without some sample input and output. – Roger Ng Mar 04 '20 at 13:29
  • @RogerNg you wouldn't always find an answer in a single question, but if only you would have started with an attempt you might have reached the other. Notice, I'd mentioned two links for marking this as a duplicate. (Primary motive - "Make an attempt!") – Naman Mar 04 '20 at 13:31

2 Answers2

5

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]
Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can do it as follows:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("1,2", "3,4", "5");
        List<String> newList = new ArrayList<String>();
        list.forEach(s -> Arrays.stream(s.split(",")).forEach(newList::add));
        System.out.println(newList);
    }
}

Output:

[1, 2, 3, 4, 5]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110