List Delete repeating elements

Source: Internet
Author: User
Tags addall set set

Method One: Loop element deletion
Delete duplicate elements in ArrayList
public static void RemoveDuplicate1 (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);
}

Java removes list duplicate values
Two ways, one without order, and one to maintain the order of elements in the original list.

Hastset according to Hashcode, the data is not duplicated.

public static void Removeduplicate (ArrayList arllist)
{
HashSet h = new HashSet (arllist);
Arllist.clear ();
Arllist.addall (h);
}


Use the Add method of HashSet to determine if the same data has been added, and if the same data already exists, do not add


public static void Removeduplicatewithorder (ArrayList arllist)
{
Set set = new HashSet ();
List NewList = new ArrayList ();
for (Iterator iter = Arllist.iterator (); Iter.hasnext ();)
{
Object element = Iter.next ();
if (Set.add (Element)) Newlist.add (element);
}
Arllist.clear ();
Arllist.addall (NewList);
}

List Delete repeating elements

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.