我有一个字符串:
String modulesToUpdate = "potato:module1, tomato:module2";
我想只获取以下内容:
module1
module2
首先,我需要用“,”分割它,然后再用“:”分割。
所以,我做了这个:
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])
}
}
这样做是可行的,但嵌套循环不够优雅。
我正在尝试使用流(Streams)完成相同的操作。
于是,我做了这个:
Stream.of(modulesToUpdate)
.map(line -> line.split(","))
.flatMap(Arrays::stream)
.flatMap(Pattern.compile(":")::splitAsStream)
.forEach(f-> System.out.println(f.toString().trim()));
输出:
potato
module1
tomato
module2
如何减少/过滤以仅获取以下内容:
module1
module2
.map(s -> s.substring(s.indexOf(':')+1))
,因为它不会创建数组和无关的子字符串。 - Holger