2012-01-30 113 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. 
相关问题