首页 > 解决方案 > 从两个列表的组合中形成新的小列表

问题描述

我在一个大列表中有两种列表模式。

[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]

简单地说,它是一个组合

[ [pricesList1],[DurationList1],[PricesList2],[DurationList2],...]

我现在想创建一个新列表,其中包含两个列表中的价格和相应的持续时间作为每组中的一对。例如 :

[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]

我试过使用List<List<Object>>and List<List<String>>。但是没有用。我怎样才能做到这一点?

我编程如下,这是错误的:

List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
                {
                    for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
                            {
                            SlotList = new ArrayList<List<String>>();
                            SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
                            }
                }
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
                {
                    for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
                            {
                            SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
                            }
                }

标签: javalistarraylist

解决方案


假设输入列表总是有偶数个子列表并且子列表对具有相同的大小,您可以使用一个for循环遍历外部列表的元素两两:

List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
    List<String> priceList = outerList.get(i);
    List<String> durationsList = outerList.get(i+1);
    for (int j=0; j<priceList.size(); j++) {
        List<String> newEntry = new ArrayList<>();
        newEntry.add(priceList.get(j));
        newEntry.add(durationsList.get(j));
        result.add(newEntry);
    }
}

正如评论的那样,我建议定义您自己的类来存储价格和持续时间,而不是使用它List<String> newEntry


推荐阅读