oma07 oma07 - 4 months ago 13
Java Question

Retrieving inner elements in java

In a list of arrays, in java, is there a way I can get a list which is composed of all the ith elements on the arrays that comprise my original list?

For example (pseudo code):

input:

List<int[3]> A = {[1,2,3], [2,3,5], [1,0,7]}
i = 2


output:

B = {2,3,0}


I will really like to achieve this without explicitly looping. Any ideas?

Answer

You could use streams:

int i = 2;
List<Integer> listB = listA.stream()
    .filter(arr -> arr.length > i) // (Optional) Filter out arrays that are too small.
    .map(arr -> arr[i]) // Get element at index i.
    .collect(Collectors.toList()); // Collect into a list.