ArrayList迭代特定列表

时间:2015-10-01 10:59:37

标签: java list loops arraylist

我有一个arraylist

ArrayList<ArrayList<String>> listofItems=new ArrayList<ArrayList<String>>();

在项目列表中我有这样的项目

[[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [ 16] [17] [18] [19] [20] [21] [22]]

如何迭代并存储在另一个数组中,这些值分为两个,如

[1,2,3,4,5,6,7,8,9,10,11]和[11,12,13,14,15,16,17,18,19,20,21, 22。我使用了高级for循环

for(ArrayList<String> list:listofItems)
{

for (String s:list)
{

//I dont know how to add logic here.

}

}

4 个答案:

答案 0 :(得分:1)

我在这里假设两个列表也将保存字符串类型数据。如果你想要Integer类型,你可以在添加时进行解析。

ArrayList<ArrayList<String>> listofItems = new ArrayList<ArrayList<String>>();
            ArrayList<String> list1 = new ArrayList<String>();
            ArrayList<String> list2 = new ArrayList<String>();
            for (ArrayList<String> list : listofItems) {

                for (String s : list) {
                    // there shud be some condition how much elements you want in a
                    // list or some condition
                    // to decide in which list we need to add item
                    if (list.size() < 12)
                        list1.add(s);
                    else
                        list2.add(s);

                }

            }

答案 1 :(得分:0)

使用类似的东西:

if (yourlist.size()>0) {
   List<String> first = yourList.subList(0, (int)Math.ceil(yourlist.size()/2.0));
   List<String> second = yourList.subList((int)Math.ceil(yourlist.size()/2.0), yourlist.size());
}

将您的列表分成两个分为两半的列表。

答案 2 :(得分:0)

您可以使用此代码将列表存储到另一个列表中。

List<String> stringList = new ArrayList<String>();
for(ArrayList<String> list:listofItems) {
  for (String s:list) {
    stringList.add(s);
  }
}

答案 3 :(得分:0)

在这种情况下,当您向listOfItems添加信息时,您应该尝试这样的示例

    for(int i = 0; i< 2; i++){
        for(int j = 0; j < n; j++){
            /// add util break n
            lists.get(i).add(strTemp);
        }
    }

您可以将i < 2更改为您想要的任何数字。我只为你制作这个样品。