Java stream - get result after splitting a string twice

I have a line:

String modulesToUpdate = "potato:module1, tomato:module2";

I want to get only from him:

module1
module2

First I need to break it into "," and then into ":"

So, I did this:

String files[] = modulesToUpdate.split(",");

for(String file: files){
    String f[] = file.split(":");
    for(int i=0; i<f.length; i++){
        System.out.println(f[1])
    }
}

This works, but the loop in the loop is not elegant.

I am trying to do the same with threads.

So, I did this:

Stream.of(modulesToUpdate)
            .map(line -> line.split(","))
            .flatMap(Arrays::stream)
            .flatMap(Pattern.compile(":")::splitAsStream)
            .forEach(f-> System.out.println(f.toString().trim()));

Output:

potato
module1
tomato
module2

How to reduce / filter it to get only:

module1
module2
+6
source share
4 answers

Change one line:

  .map(x -> x.split(":")[1])

instead:

  .flatMap(Pattern.compile(":")::splitAsStream)

Or as @Holger mentions in a comment:

 .map(s -> s.substring(s.indexOf(':')+1))

it does not create an intermediate array at all.

That flatMapreturns Stream, and the streams have no indexes, but in this case you need them to go to the second token.

+7
source

split .

,\s* ,, trim. , ( [^:]*?:) , .

: , . ,

Pattern.compile(",\\s*[^:]*?:")
       .splitAsStream(modulesToUpdate.substring(modulesToUpdate.indexOf(':')+1))
       .forEach(System.out::println);

, , ,

Pattern.compile("(^|,\\s*)[^:]*?:").splitAsStream(modulesToUpdate)
       .skip(1)
       .forEach(System.out::println);
+4

skip flatMap, :

String modulesToUpdate = "potato:module1, tomato:module2";
Arrays.stream(modulesToUpdate.split(","))
.map(String::trim)
.flatMap(s -> Arrays.stream(s.split(":")).skip(1))
.forEach(System.out::println);
+3

, :

  • Array flow and collection of elements in odd positions

String modulesToUpdate = "potato:module1, tomato:module2";
String[] mod = modulesToUpdate.split("[:,]");
List<String> res = IntStream.range(0, mod.length)
                     .filter(j -> (j % 2) == 0)
                     .mapToObj(i -> mod[i])
                     .collect(Collectors.toList());
System.out.println(res);
+1
source

All Articles