Java stream – the result is obtained after splitting the string twice
•
Java
I have a string:
String modulesToUpdate = "potato:module1,tomato:module2";
I want to get it from it:
module1 module2
First, I must 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 the loop in the loop is not elegant
I'm trying to do the same thing with stream
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 only gets:
module1 module2
Solution
Change one line:
.map(x -> x.split(":")[1])
Substitute:
.flatMap(Pattern.compile(":")::splitAsStream)
Or @ Holger mentioned in the comment:
.map(s -> s.substring(s.indexOf(':')+1))
This does not create intermediate arrays at all
The flatmap returns a stream and streams without an index, but in this case you need them to get the second tag
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码