1

嗨,我有两个 ArrayList 对象,我需要将其合并为一个列表。这是我的要求

我的第一个清单

列表A

{StaffFirstName=f2, resourceId=2, totalcost=18055.0, totalPercentageInvolvment=550, ResourceCost=2300, staffRole=tl}

和列表B

{sixthmonth=60, fourthmonth=40, firstmonth=10, fifthmonth=50, secondmonth=20, `thirdmonth=30}`

我需要结果是

结果

{StaffFirstName=f2, resourceId=2, totalcost=18055.0, totalPercentageInvolvment=550, ResourceCost=2300, staffRole=tl, sixthmonth=60, fourthmonth=40, firstmonth=10, fifthmonth=50, secondmonth=20, thirdmonth=30}

编辑!

实际上我的两个列表都是 arrayList 所以我的 listA 将是

{StaffFirstName=f2, resourceId=2, totalcost=18055.0, totalPercentageInvolvment=550, ResourceCost=2300, staffRole=tl}
{StaffFirstName=demo35, resourceId=3, totalcost=19625.0, totalPercentageInvolvment=785, ResourceCost=2500, staffRole=sweeper}

列表 B 将是

{sixthmonth=100, fourthmonth=30, firstmonth=40, fifthmonth=25, secondmonth=100, thirdmonth=90}
{sixthmonth=100, fourthmonth=30, firstmonth=40, fifthmonth=25, secondmonth=100, thirdmonth=90}

结果应该是

{StaffFirstName=f2, resourceId=2, totalcost=18055.0, totalPercentageInvolvment=550, ResourceCost=2300, staffRole=tl, sixthmonth=60, fourthmonth=40, firstmonth=10, fifthmonth=50, secondmonth=20, thirdmonth=30}
{StaffFirstName=demo35, resourceId=3, totalcost=19625.0, totalPercentageInvolvment=785, ResourceCost=2500, staffRole=sweeper, sixthmonth=100, fourthmonth=30, firstmonth=40, fifthmonth=25, secondmonth=100, thirdmonth=90}

这意味着我的拖车列表的每一行都必须明智地附加我的行。如果我使用addAll函数,两个列表就像这样附加

{StaffFirstName=f2, resourceId=2, totalcost=18055.0, totalPercentageInvolvment=550, ResourceCost=2300, staffRole=tl}
{StaffFirstName=demo35, resourceId=3, totalcost=19625.0, totalPercentageInvolvment=785, ResourceCost=2500, staffRole=sweeper}
{sixthmonth=60, fourthmonth=40, firstmonth=10, fifthmonth=50, secondmonth=20, thirdmonth=30}
{sixthmonth=100, fourthmonth=30, firstmonth=40, fifthmonth=25, secondmonth=100, thirdmonth=90}. But i need to append the two list row wise. Is it possible?
4

4 回答 4

9

鉴于:

   List<MyClass> listA, listB;

尝试这个:

   List<MyClass> union = new ArrayList<MyClass>();
   union.addAll( listA );
   union.addAll( listB );

编辑(Java 8 或更高版本)

在 Java 8 或更高版本中,您可以使用流将列表连接到单个表达式中。

List<MyClass> union = Stream.concat( listA.stream(), listB.stream())
            .collect( Collectors.toList());
于 2012-07-10T13:16:57.163 回答
3

我不太确定你所拥有的是一个ArrayList(来自输出),但即便如此,如果它是一个实现Collection接口的类,你可以使用该addAll方法,独立于确切的类(只要对象是同类型)。

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#addAll(java.util.Collection , T...)

于 2012-07-10T13:18:20.877 回答
2

如果这些是包含相同类型的 ArrayList<> 对象,则可以使用:

list1.addAll(list2);

它应该可以很好地满足您的需求。

于 2012-07-10T13:16:26.657 回答
0

类型是数组的类型......

 Type[] concat(Type[] listA, Type[] listB) 
     {
       Type[] list= new Type[listA.length+listB.length];
       System.arraycopy(listA, 0, list, 0, listA.length);
       System.arraycopy(listB, 0, list, listA.length, listB.length);

       return list;
     }
于 2012-07-10T13:19:54.573 回答