Skip to content

Instantly share code, notes, and snippets.

@brandhill
Created August 18, 2014 06:01
Show Gist options
  • Save brandhill/3e59f8bdca5050e6ec5c to your computer and use it in GitHub Desktop.
Save brandhill/3e59f8bdca5050e6ec5c to your computer and use it in GitHub Desktop.
Merging two arrayLists into a new arrayList, with no duplicates (Java)
// 方法 1
ArrayList al = new ArrayList();
// add elements to al, including duplicates
HashSet hs = new HashSet();
hs.addAll(al);
al.clear();
al.addAll(hs);
// 方法 2
//Add ArrayList1, ArrayList2 and produce a Single arraylist ArrayList3. Now convert it into
Set Unique_set = new HashSet(Arraylist3);
// 方法 3
//Firstly remove duplicates:
arrayList1.remove(arrayList2);
//Then merge two arrayList:
arrayList1.addAll(arrayList2);
//Lastly, sort your arrayList if you wish:
collections.sort(arrayList1);
//In case you don't want to make any changes on the existing list, first create their backup lists:
arrayList1Backup = new ArrayList(arrayList1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment