Skip to content
Advertisement

Get every nth element of nested lists using Java Streams

Here’s a function that will take a nested ArrayList allLists, an index nth, and return the nth element of every sublist.

E.g. for allLists = {{1,2,3}, {4,5,6}, {7,8,9}}, nth = 1, the function will return {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;
    }

I’ve managed to get a version working where I can print it out:

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

How to gather the results into an array?

Answer

Solved:

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]);
}
Advertisement