Merge 3 arraylist to one
43,222
Solution 1
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);
Solution 2
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);
Solution 3
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>
Author by
snake plissken
Updated on September 10, 2020Comments
-
snake plissken over 3 years
I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?
-
Erick G. Hagstrom about 8 yearsI'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 singleList<T>
with all of the elements of the originals, or about making aList<List<T>>
containing each of the originals? -
Erick G. Hagstrom about 8 yearsIs it important that the output be an instance of
ArrayList<something>
rather than just aList
?
-
-
snake plissken over 12 yearsXm I thik this solutions is about creating a 2d Arraylist. I want to put side by side 3 lists to one new.
-
Asaph over 12 years@snake plissken: You made no mention of 2D lists in the question. However, I've updated my answer to include a 2D solution too.
-
ziesemer over 12 years@snakeplissken - This answer will do what you expect, no 2D involved.
-
Michael Massey almost 9 yearsThis is much better than the first answer. It is a much cleaner way of merging lists into a 2D list.
-
Tim over 8 yearsNote: you would normally call this as
Arrays.asList()
-
Erick G. Hagstrom about 8 yearsNote that this results in a fixed size
List<List<String>>
, not anArrayList<ArrayList<String>>
. OP specifically calls forArrayList
. I'm not sure whether they want 1D or 2D, but definitelyArrayList
.