Java removes duplicate elements from list

Source: Internet
Author: User

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

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.