如何从二维arraylist中的特定位置提取整数?

时间:2012-01-30 11:36:15

标签: java arrays arraylist iterator

如果我有ArrayList ArrayList个说“大名单”。

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

我如何计算第一行中的所有1(所以1 4 5 6 7,总共1个1),第二行相同?

我输了,所以任何帮助或指导都会受到赞赏。

3 个答案:

答案 0 :(得分: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 */));
}

答案 1 :(得分: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视为矩阵。

答案 2 :(得分:0)

  

我如何计算第一行中的所有1(所以1 4 5 6 7,总共1个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.