簡體   English   中英

將嵌套循環轉換為流 Java 8

[英]Convert nested loops into streams Java 8

我正在嘗試將下面的嵌套循環轉換為流 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的新列表中?

非常感謝任何幫助。

這是我的做法:

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

這是其他解決方案。

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());

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM