2016-07-22 36 views
1

在java中的數組列表中,有沒有一種方法可以獲得由構成我的原始列表的數組上的所有第i個元素組成的列表?檢索java中的內部元素

例如(僞代碼):

輸入:

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

輸出:

B = {2,3,0} 

我真的想實現這一點沒有明確地寫一個for循環或while循環或任何其他常規循環結構。有任何想法嗎?

+1

你是什麼意思,沒有明確的循環? – Compass

+0

你試過自​​己解決這個問題嗎? –

+0

你是否想要找到一種內置於Java'List'類的方法來爲你做這件事? –

回答

3

你可以使用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. 
+0

謝謝!這工作。就像C#中的LINQ一樣。謝謝你的幫助 :) – oma07

0

之前的Java 8,那麼你必須比去在名單和採摘的每一個元素在希望的位置沒有其他辦法:

例子:

之前Java8

public static void main(String[] args) { 

List<int[]> aL = new ArrayList(); 
aL.add(new int[] { 1, 2, 3 }); 
aL.add(new int[] { 2, 3, 5 }); 
aL.add(new int[] { 1, 0, 7 }); 
int index = 1; 
List<Integer> aLFinal = new ArrayList(); 

for (int[] i : aL) { 
    aLFinal.add(i[index]); 
} 
System.out.println("the list before java8 " + aLFinal); 
} 

後Java8

aLFinal = aL.stream().map(arr -> arr[index]).collect(Collectors.toList()); 
System.out.println("the list after java8 " + aLFinal); 
0

希望這是你所需要的

public List<Integer> getYourResult(List<Integer[]> yourList, int index) { 
    if (index >= 3) return null; 
    List<Integer> result = new ArrayList<>(); 
    for (int i = 0; i < yourList.size(); ++i) { 
     result.add(i, yourList.get(i)[index]); 
    } 
    return result; 
}