简体   繁体   中英

Split a stream if it contains multiple comma-separated values

This code will add all elements from mylist to mylist2.

How can I change it to add elements if it finds a comma, and separates them?

ArrayList<String> mylist = new ArrayList<String>();
mylist.add("test");
mylist.add("test2, test3");
ArrayList<String> mylist2 = new ArrayList<String>();

mylist.stream()
    .forEach(s -> mylist2.add(s));

mylist2.stream().forEach(System.out::println);

So, current output is:

test
test2, test3

and I need the second arraylist to contain and then print:

test
test2
test3

I know in Java 8 there are filters. Could I do something like

.filter(p -> p.contains(",")... then something to split it?

You could do a flatMap including a Pattern::splitAsStream like

Pattern splitAtComma = Pattern.compile("\\s*,\\s*");
List<String> myList2 = mylist.stream().flatMap(splitAtComma::splitAsStream)
                         .collect(Collectors.toList());

You could split each string and flatMap the resulting array:

mylist.stream()
      .flatMap(x -> Arrays.stream(x.split(", ")))
      .forEach(System.out::println);

You can use :

mylist.forEach(str -> mylist2.addAll(Arrays.asList(str.split("\\s*,\\s*"))));

Output

test
test2
test3

and I need the second arraylist to contain and then print:

You could create two streams : one for creating the target List and another one for displaying it.

List<String> list2 = mylist.stream()
    .flatMap(x -> Arrays.stream(x.split(", ")))
    .collect(Collectors.toList());

list2.stream().forEach(System.out::println);

or with one stream by using peak() to output the element of the Stream before collecting into a List :

List<String> list2 = mylist.stream()
    .flatMap(x -> Arrays.stream(x.split(", ")))
    .peek(System.out::println)
    .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM