Two ways to remove the same elements in the list in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.