2012-01-30 110 views
0

如果我有ArrayListArrayList s說「biglist」。如何從二維數組列表中的特定位置提取整數?

[[1,2,3],[4,3,2],[5,1,2],[6,4,7],[7,1,2]] 

如何我能相符的所有的1的第一行中(所以1 4 5 6 7,共爲一體1),和相同的用於第二等?

我失去了這個,所以任何幫助或指導,將不勝感激。

+0

一在列表的所有維上嵌套for循環可以計算每個外觀 – Hachi 2012-01-30 11:38:39

+0

@gary僅使用2 for循環,第1個循環迭代所有行。第二個循環迭代所有列,並檢查是否有任何列值= 1。如果等於1,那麼計數一個並繼續下一行的行循環 – 2012-01-30 11:43:58

+0

是的我可以做到這一點,但我希望它可以縮放(我給出的例子很小),並且我可能正在尋找其他行中的其他值) – 2012-01-30 12:05:43

回答

1
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); 
//...add your integer to the list 

ArrayList<Integer> newList = new ArrayList<Integer>(); 
for(int i = 0; i < list.size(); i++) 
{ 
    if(i == 2 || i == 3) //for instance if you want to exclude certain sublists in your list 
     continue; 

    ArrayList<Integer> ints = list.get(i); 
    if(ints.size() > 0) 
     newList.add(ints.get(0 /* 0 or whatever part of inner list you want */)); 
} 
+0

這將是完美的,如果有一種方法,我可以限制它只能從某些行 – 2012-01-30 12:06:24

+0

我不確定這是你想要的,但看到我的編輯。 – 2012-01-30 12:13:43

1

你有沒有嘗試過這樣的:

public ArrayList<ArrayList<Integer>> getElements(ArrayList<ArrayList<Integer>> bigList, int columnIndex){ 
    ArrayList<Integer> resultList = new ArrayList<Integer>(); 
    for (ArrayList<Integer> al : bigList){ 
     resultList.add(al.get(columnIndex)); 
    } 
    return resultList; 
} 

注:我說columnIndex因爲我看到了你的bigList作爲基質。

+0

不,不幸的是,它是指定arrayList的arrayList列表 – 2012-01-30 12:09:46

+0

@GaryJones對不起,我更正了我的代碼! – davioooh 2012-01-30 13:43:10

0

我怎麼能在第一行中記錄所有的1(所以1 4 5 6 7,總共是1),第二行中的相同?

你可以指望你使用類似連續特定數量看的次數:

int intWeAreLookingFor = 1; 
int rowNumber=0; 
for(ArrayList list: biglist){ 

    int numOfHits=0; 
    rowNumber++; 
    for(Integer i: list){ 

     if(i.equals(intWeAreLookingFor)){ 
      numOfHits++; 
     } 
    } 
    System.out.printLine("The number '"+intWeAreLookingFor 
     +"' was counted "+numOfHits+" times in row "+rowNumber+"."); 
} 

爲您的樣品陣列[[1,2,3],[4,3,2],[5,1,2],[6,4,7],[7,1,2]],這會打印出:

The number '1' was counted 1 times in row 1. 
The number '1' was counted 0 times in row 2. 
The number '1' was counted 1 times in row 3. 
The number '1' was counted 0 times in row 4. 
The number '1' was counted 1 times in row 5. 
相關問題