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?

Asaph
  • 159,146
  • 25
  • 197
  • 199
snake plissken
  • 2,649
  • 10
  • 43
  • 64
  • 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` and making a single `List` with all of the elements of the originals, or about making a `List>` containing each of the originals? – Erick G. Hagstrom Feb 26 '16 at 14:44
  • Is it important that the output be an instance of `ArrayList` rather than just a `List`? – Erick G. Hagstrom Feb 26 '16 at 14:57

3 Answers3

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
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
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