Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge 3 arraylist to one

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

like image 236
snake plissken Avatar asked Dec 24 '11 15:12

snake plissken


People also ask

How do you combine ArrayList?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

Can you use .equals for ArrayList?

You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.


Video Answer


2 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); 
like image 54
Asaph Avatar answered Sep 18 '22 00:09

Asaph


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); 
like image 20
Edwin Dalorzo Avatar answered Sep 20 '22 00:09

Edwin Dalorzo