我正在尝试将以下嵌套循环转换为流Java 8.
newself2中的每个元素都是字符串列表 - [" 1 2"," 3 4"]需要更改为[" 1",&# 34; 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"]...]
}
到目前为止我一直在尝试 -
newself2.streams().forEach(list -> list.foreach(y -> y.split(" ")))
现在我现在确定如何将内部for循环中的split数组添加到x
的新列表中?
非常感谢任何帮助。
答案 0 :(得分:4)
我是这样做的:
List<List<String>> result = newself2.stream()
.map(list -> list.stream()
.flatMap(string -> Arrays.stream(string.split(" ")))
.collect(Collectors.toList()))
.collect(Collectors.toList());
答案 1 :(得分:1)
这是其他解决方案。
Function<List<String>,List<String>> function = list->Arrays.asList(list.stream()
.reduce("",(s, s2) -> s.concat(s2.replace(" ",",")+",")).split(","));
并使用此功能
List<List<String>> finalResult = lists
.stream()
.map(function::apply)
.collect(Collectors.toList());
带有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(",")));
}