If set is used, if the element inside the list is not a basic data type but an object,
Then overwrite the boolean equals (object obj) and int hashcode () methods of object.
return new ArrayList (new HashSet (list));
method One : Looping elements delete
// Delete duplicate element in ArrayList;
public static void removeduplicate ( list list) { for ( int i = 0 ; i < List.size () - 1 ; i ++ ) { for ( int j = list.size () - 1 ; j > i; j -- ) { if (List.get (j). Equals (List.get (i))) { list.remove (j); } } } system.out.println (list);}
Method two : through HashSet culling
// Delete duplicate element in ArrayList;
public static void Removeduplicate (List list) {HashSet h = new HashSet (list); List.clear (); List.addall (h); SYSTEM.OUT.PRINTLN (list);}
Method Three : Delete duplicate elements in ArrayList, keep order
Delete duplicate elements in ArrayList, keep order
public static void Removeduplicatewithorder (list list) { set set = new hashset (); list newlist = new arraylist (); for (Iterator iter = list.iterator (); iter.hasnext ();) { object element = iter.next (); if (Set.add (Element)) newlist.add (Element); } list.clear (); list.addall (newList); system.out.println ( " remove duplicate " + list);}
If you are using HashSet, if you are an object, implement the Equals and Hashcode methods for the object.
Java removes duplicate elements from list