This example shows how to remove duplicate elements from a list object.
import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class CreateUniqueList { public static void main(String[] args) { /** Create a ArrayList object **/ ArrayList< string > arrayList = new ArrayList< string >(); /** Add elements to ArrayList.ArrayList occupies duplicate elements. **/ arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); arrayList.add("D"); arrayList.add("A"); /** * HashSet(Collection c) - Constructs a new set containing the unique * elements in the specified collection. A set is a collection object * that cannot have a duplicate values, so by converting the list to a * set the duplicate value will be removed. **/ Set set = new HashSet(arrayList); System.out.println("The set contains..." + set); } }
The output is:
The set contains...[D, A, B, C]
No comments:
Post a Comment