I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?
3 Answers
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); 3 Comments
snake plissken
Xm I thik this solutions is about creating a 2d Arraylist. I want to put side by side 3 lists to one new.
Asaph
@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
@snakeplissken - This answer will do what you expect, no 2D involved.
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
Michael Massey
This is much better than the first answer. It is a much cleaner way of merging lists into a 2D list.
Tim
Note: you would normally call this as
Arrays.asList()Erick G. Hagstrom
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.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>
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?ArrayList<something>rather than just aList?