Java ArrayList将当前项添加到Previous项;删除当前项目

时间:2014-07-17 05:05:51

标签: java arraylist merge split-apply-combine

代码的目的是通过ArrayList>中的每个项目进行迭代。 listOfLists并将先前列表与当前列表组合,对当前列表进行排序并删除下一个列表(自已合并)。这需要发生,直到只剩下一个列表。有了它,我可以将ArrayList.get(0)的内容吐出到文件中。

listOfLists是在代码片段之前定义的。 我正在努力的是:如何将alStr1内容发送回listOfLists.get(0)?

while ( listOfLists.size() > 1 ) {
    System.out.println(">>>>>>>>>>>>>Iteration"+i);
    Iterator<ArrayList<String>> itr = listOfLists.iterator();
    while(itr.hasNext()) {
        ArrayList<String> alStr1 = itr.next();
        try{
            ArrayList<String> alStr2 = itr.next();
            alStr1.addAll(alStr2);
            Collections.sort(alStr1);
            itr.remove();
        }catch (NoSuchElementException e){
            e.printStackTrace();
            break;
        }
    }
}

非常感谢任何提供的建议。 感谢

LOGIC:
------
L1 L2 L3 L4 L5 --> L1+L2 L3+L4 L5 
L1+L2 L3+L4 L5 --> L1+L3 L5 
L1+L3 L5 --> L1+L5 
L1+L5 --> L1

L1 => going to a file.

listOfLists will include these 5 lists:
L1: [100,101,102]
L2: [200,201,202]
L3: [300,301,302]
L4: [400,401,402]
L5: [500,501,502]
Iteration 1:
L1 = L1+L2>> [100,101,102,200,201,202]
L3 = L3+L4>> [300,301,302,400,401,402]
L5 = L5   >> [500,501,502]

Iteration 2:
L1 = L1+L3>> [100,101,102,200,201,202,300,301,302,400,401,402]
L5   >> [500,501,502]

Iteration 3:
L1 = L1+L5>> [100,101,102,200,201,202,300,301,302,400,401,402,500,501,502]

这可以解释我想要实现的目标。请原谅我没有先加上这个。

1 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {

            List<List<Integer>> listOfList = new ArrayList<List<Integer>>();

            Random rand = new Random(System.currentTimeMillis());

            for (int i = 0; i < 5; i++) {
                List<Integer> list = new ArrayList<Integer>();
                for (int j = 0; j < 5; j++) {
                    list.add(rand.nextInt(1000));
                }
                listOfList.add(list);
            }

            while (listOfList.size() > 1) {

                Iterator<List<Integer>> itr = listOfList.iterator();
                List<Integer> first = itr.next();

                while (itr.hasNext()) {
                    List<Integer> temp = itr.next();
                    first.addAll(temp);
                    itr.remove();
                    Collections.sort(first);
                }
            }

            List<Integer> first = listOfList.get(0);
            for (Integer integer : first) {
                System.out.print(integer + ", ");
            }
        }