[英]Convert nested loops into streams Java 8
I am trying to convert the below nested loop in to streams Java 8.我正在尝试将下面的嵌套循环转换为流 Java 8。
Each element in newself2 is a list of string - ["1 2","3 4"] needs to change to ["1","2","3","4"]. newself2中的每个元素都是一个字符串列表——["1 2","3 4"]需要改为["1","2","3","4"]。
for (List<String> list : newself2) {
// cartesian = [["1 2","3 4"],["4 5","6 8"]...] list = ["1 2","3 4"]...
List<String> clearner = new ArrayList<String>();
for (String string : list) { //string = "1 3 4 5"
for (String stringElement : string.split(" ")) {
clearner.add(stringElement);
}
}
newself.add(clearner);
//[["1","2","3","4"],["4","5","6","8"]...]
}
What I have tried till now -到目前为止我所尝试的 -
newself2.streams().forEach(list -> list.foreach(y -> y.split(" ")))
Now I am now sure how to add the split array in the inner for loop to a new list for x
?现在我确定如何将内部 for 循环中的拆分数组添加到
x
的新列表中?
Any help is greatly appreciated.非常感谢任何帮助。
Here's how I'd do it:这是我的做法:
List<List<String>> result = newself2.stream()
.map(list -> list.stream()
.flatMap(string -> Arrays.stream(string.split(" ")))
.collect(Collectors.toList()))
.collect(Collectors.toList());
This is other solution.这是其他解决方案。
Function<List<String>,List<String>> function = list->Arrays.asList(list.stream()
.reduce("",(s, s2) -> s.concat(s2.replace(" ",",")+",")).split(","));
and use this function并使用此功能
List<List<String>> finalResult = lists
.stream()
.map(function::apply)
.collect(Collectors.toList());
with for
loop is similar to this: with
for
循环类似于:
List<List<String>> finalResult = new ArrayList<>();
for (List<String> list : lists) {
String acc = "";
for (String s : list) {
acc = acc.concat(s.replace(" ", ",") + ",");
}
finalResult.add(Arrays.asList(acc.split(",")));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.