I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?
Asked
Active
Viewed 4.5k times
3 Answers
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);

Asaph
- 159,146
- 25
- 197
- 199
-
1Xm I thik this solutions is about creating a 2d Arraylist. I want to put side by side 3 lists to one new. – snake plissken Dec 24 '11 at 15:13
-
2@snake plissken: You made no mention of 2D lists in the question. However, I've updated my answer to include a 2D solution too. – Asaph Dec 24 '11 at 15:14
-
2@snakeplissken - This answer will do what you expect, no 2D involved. – ziesemer Dec 24 '11 at 15:15
10
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);

Ahmad
- 69,608
- 17
- 111
- 137

Edwin Dalorzo
- 76,803
- 25
- 144
- 205
-
This is much better than the first answer. It is a much cleaner way of merging lists into a 2D list. – Michael Massey Jul 31 '15 at 07:47
-
-
Note that this results in a fixed size `List
- >`, not an `ArrayList
>`. 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>

Dhruvan Ganesh
- 1,502
- 1
- 18
- 30
>` containing each of the originals?