Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two list into a single list

I have a ArrayList as below.

ArrayList<ArrayList<String>> a = new ArrayList<ArrayList<String>>();

Where ArrayList 'a' contains two ArrayList of string as below.

[a,b,c,d] & [1,2,3,4]

How to merge these two list into a single list as below.

[a,b,c,d,1,2,3,4]

Thanks In Advance.

like image 521
Suniel Avatar asked Nov 30 '22 00:11

Suniel


2 Answers

You combine a foreach loop and the addAll method.

Example

ArrayList<String> combined = new ArrayList<String>();

for(ArrayList<String> list : a) {
    combined.addAll(list);
}

How this works?

A for each loop will traverse through every member of a Collection. It has a temporary variable, in this case list that it assigns the current element too. All you're doing is adding every element inside each value for list, to one ArrayList named combined.

like image 78
christopher Avatar answered Dec 04 '22 07:12

christopher


Just iterate through all the inner lists of a using foreach loop and addAll to result arraylist

ArrayList<String> merged = new ArrayList<String>();

for(ArrayList<String> list : a){
   merged.addAll(list);
}

EDIT: As @Lubo pointed out.

Note that this way you can end up with many arrays being created and thrown away internally in ArrayList. If you have large lists (number of contained elements), consider looking here: Union List

like image 37
Narendra Pathai Avatar answered Dec 04 '22 06:12

Narendra Pathai