0

代码的目的是遍历 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]

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

4

1 回答 1

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 + ", ");
            }
        }
于 2014-07-17T05:38:19.470 回答