java stream - get the result after splitting string twice

Viewed 1990

I have a String:

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

I want to get from it only:

module1
module2

First I have to split it with "," and then with ":"

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 loop in the loop is not elegant.

I'm trying to do the same thing with streams.

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
4 Answers
Related