将嵌套循环转换为Java 8中的流

3
我将尝试将下面的嵌套循环转换为Java 8中的流。
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"]...]
}

到目前为止我尝试过的方法 -

newself2.streams().forEach(list -> list.foreach(y -> y.split(" ")))  

现在我不确定如何将内部 for 循环中的分割数组添加到一个新列表中的 x

非常感谢任何帮助。

2个回答

8

这是我会这样去做:

List<List<String>> result = newself2.stream()
    .map(list -> list.stream()
            .flatMap(string -> Arrays.stream(string.split(" ")))
            .collect(Collectors.toList()))
    .collect(Collectors.toList());

1
首先感谢您的回答!它完美地解决了我的问题! 但是我仍然想知道 - 因为我是新手 - 这是否是最优的方法?有没有可能进一步加快速度? - Paul Alwin
2
@PaulAlwin 流式处理由于需要创建所有内部基础架构来完成其工作,因此具有一定的开销。因此,for循环通常具有更好的性能。另一方面,流操作易于并行化,并且可以更好地扩展。关于我的解决方案的复杂性,它与您的相同,即与以空格分隔的元素数量成线性关系。 - fps

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(",")));
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接