Two methods in Java to delete the same element in the list, one to maintain the order of the elements in the list, and the other to not maintain the order of the elements in the list.
package stage3;import java.util.iterator;public class removetheelement {public Static <e> void removeduplicatewithoutorder (java.util.list<e> list) { Java.util.set<e> set = new java.util.hashset<e> (list); List.clear (); list.addAll (set);} Public static <e> void removeduplicatewithorder (Java.util.list<e> list) {java.util.Set<E> set = new java.util.HashSet<E> (java.util.list<e); > newList = new java.util.Vector<E> ();iterator<e> iter = List.iterator ();while (Iter.hasnext ()) {e element = iter.next ();if (Set.add ( Element)) {newlist.add (element);}} List.clear (); List.addall (newlist);} Public static void main (String[] args) {java.util.arraylist<string> list1 = new java.util.ArrayList<> (); String str = "The apple and the banana"; System.out.println ("Source:" + str); List1.addall (Java.util.Arrays.asList (Str.split (" ")); Removetheelement.removeduplicatewithoutorder (List1); System.out.print ("target:");for (String s : list1) {system.out.print (s + " ");} System.out.println (); java.util.arraylist<integer> list2 = new java.util.arraylist <> (); Integer[] num = { 1, 2, 3, 4, 3, 5, 5, 2, 1 };list2.addall (Java.util.Arrays.asList (num)); Removetheelement.removeduplicatewithorder (List2);for (int i : list2) { System.out.print (i + ",");}}}
Output comparison:
The first of these methods
Source:the Apple and the banana
Target:the Banana Apple and
The second method of
Source:1, 2, 3, 4, 3, 5, 5, 2, 1
target:1,2,3,4,5,
Two ways to remove the same elements in the list in Java