nidis :
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
Eugene :
Change a single line:
.map(x -> x.split(":")[1])
instead of:
.flatMap(Pattern.compile(":")::splitAsStream)
Or as @Holger mentions in the comment:
.map(s -> s.substring(s.indexOf(':')+1))
this does not create the intermediate array at all.
That flatMap
is returning a Stream
and Streams don't have indexes, but you do need them in this case to get to the second token.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=465638&siteId=1