簡體   English   中英

使用 Java Streams 獲取嵌套列表的每個第 n 個元素

[英]Get every nth element of nested lists using Java Streams

這是一個 function ,它將采用嵌套的 ArrayList allLists ,一個索引nth ,並返回每個子列表的第 n 個元素。

例如對於allLists = {{1,2,3}, {4,5,6}, {7,8,9}} , nth = 1 ,function 將返回{2,5,8}

public static String[] getEveryNthElement(ArrayList<ArrayList<String>> allLists, int nth) {
        String[] nthList = new String[allLists.size()];
        int n = 0;
        for (ArrayList<String> sList: allLists) {
            if (nth <= sList.size()) {
                nthList[n] = (sList.get(nth));
            }
            n += 1;
        }
        return nthList;
    }

我已經設法得到一個可以打印出來的版本:

group.stream()
    .forEach(items -> {
        System.out.println(items.get(1));  // prints 2, 5, 8
});

如何將結果收集到數組中?

解決了:

public static String[] getEveryNthElement(ArrayList<ArrayList<String>> allLists, int nth) {
    return allLists.stream()
            .map(list -> list.get(nth))
            .collect(Collectors.toList()
    ).toArray(new String[0]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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