31

I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?

2
  • 1
    I'm confused. The question says nothing about 2D lists, but the accepted answer and comments discuss 2D, and the other answer is exclusively for 2D lists. So, is this about taking some number of List<T> and making a single List<T> with all of the elements of the originals, or about making a List<List<T>> containing each of the originals? Commented Feb 26, 2016 at 14:44
  • Is it important that the output be an instance of ArrayList<something> rather than just a List? Commented Feb 26, 2016 at 14:57

3 Answers 3

55

Use ArrayList.addAll(). Something like this should work (assuming lists contain String objects; you should change accordingly).

List<String> combined = new ArrayList<String>(); combined.addAll(firstArrayList); combined.addAll(secondArrayList); combined.addAll(thirdArrayList); 

Update

I can see by your comments that you may actually be trying to create a 2D list. If so, code such as the following should work:

List<List<String>> combined2d = new ArrayList<List<String>>(); combined2d.add(firstArrayList); combined2d.add(secondArrayList); combined2d.add(thirdArrayList); 
Sign up to request clarification or add additional context in comments.

3 Comments

Xm I thik this solutions is about creating a 2d Arraylist. I want to put side by side 3 lists to one new.
@snake plissken: You made no mention of 2D lists in the question. However, I've updated my answer to include a 2D solution too.
@snakeplissken - This answer will do what you expect, no 2D involved.
11

What about using java.util.Arrays.asList to simplify merging?

List<String> one = Arrays.asList("one","two","three"); List<String> two = Arrays.asList("four","five","six"); List<String> three = Arrays.asList("seven","eight","nine"); List<List<String>> merged = Arrays.asList(one, two, three); 

3 Comments

This is much better than the first answer. It is a much cleaner way of merging lists into a 2D list.
Note: you would normally call this as Arrays.asList()
Note that this results in a fixed size List<List<String>>, not an ArrayList<ArrayList<String>>. OP specifically calls for ArrayList. I'm not sure whether they want 1D or 2D, but definitely ArrayList.
4

Using Java 8 Streams:

List of List

List<List<String>> listOfList = Stream.of(list1, list2, list3).collect(Collectors.toList()); 

List of Strings

List<String> list = Stream.of(list1, list2, list3).flatMap(Collection::stream).collect(Collectors.toList()); 

Using Java 9 List.of static factory method (Warning: this list is immutable and disallows null)

List<List<String>> = List.of​(list1, list2, list3); 

Where list1, list2, list3 are of type List<String>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.