0

Scenario: got two lists as following:

List<Object[]> listOne = null;
List<Object[]> listTwo = null;

aMethod (see at the bottom) is invoked on each lists which returns a compatible type list

listOne = aMethod(arg1, arg2, arg3);
listTwo = aMethod(argx, argy, argz);

When i try

listOne.add(listTwo);

I get error about the add function . Recommends to use addAll(), which i cant use for my reasons. So, any one have idea how to add a list of objects [] to another list of objects []? Thanks.

public List<Object[]> aMethod(a1, a2, a3) {
        List<Object[]> aList = service.getSomeinfo();
        return aList;
    }
3
  • Your question is unclear - you want to add all items of the second list to the first list? Commented Jun 16, 2020 at 3:58
  • Currently, listOne = aMethod(arg1, arg2, arg3); is part of the code. It is processed as for(Object[] obj : listOne) down the road. Wonder if I use addAll(), will for(Object[] obj : listOne) will work as before? Commented Jun 16, 2020 at 4:13
  • Why can't you use addAll() ? Commented Jun 16, 2020 at 7:16

3 Answers 3

4

If you do not want to use addAll() method then @Shubbi you can add the second list of object array through the iteration like this :

for(Object[] o:listTwo){
    listOne.add(o);
}

There is another way and is very efficient also by using Stream Api if you are using Java 8 or upper version

listOne = Stream.concat(listOne.stream(), listTwo.stream())
                .collect(Collectors.toList());  
Sign up to request clarification or add additional context in comments.

Comments

1

Use Stream

listOne = Stream.concat(listOne.stream(), listTwo.stream())
                         .collect(Collectors.toList());

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Comments

1

You can use addAll function of list which adds all the elements of one array to other.

listOne.addAll(listTwo);

listOne will contain elements from both the lists.
You could add both list to third list as:

List<Object[]> listThree = new ArrayList<Object[]>(listOne);
listThree.addAll(listTwo);

Refer: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#addAll-java.util.Collection-

4 Comments

as mentioned above, you can add both listOne and listTwo to listThree. It wont have any effect on other two lists.
if listOne.addAll(listTwo); then listThree.addAll(listTwo); will not be ncecessory. right?
@Shubbi The above two are totally 2 different ways of adding OR merging two list. Please dont combine them into a single example.
First one adds two list in listOne. Second one adds both the list in listThree. Select either first or second

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.