2种种Java删除删除ArrayList中的重复元素的方法中的重复元素的方法
主要介绍了2种Java删除ArrayList中的重复元素的方法,感兴趣的朋友可以参考下
这篇文章将给出两种从这篇文章将给出两种从ArrayList中删除重复元素的方法,分别是使用中删除重复元素的方法,分别是使用HashSet和和LinkedHashSet。。
ArrayList是Java中最常用的集合类型之一。它允许灵活添加多个null元素,重复的元素,并保持元素的插入顺序。在编码时我
们经常会遇到那种必须从已建成的ArrayList中删除重复元素的要求。
方法方法1:使用:使用HashSet删除删除ArrayList中重复的元素中重复的元素
在该方法中,我们使用HashSet来删除重复的元素。如你所知,HashSet不允许有重复的元素。我们使用HashSet的这个属性
来删除已建 成的ArrayList中的重复元素。但是,这种方法有一个缺点。那就是,它会删除ArrayList中元素的插入顺序。这意
味着,删除重复的元素后,元 素的插入顺序就不对了。先来看下面这个例子。
import java.util.ArrayList;
import java.util.HashSet;
public class MainClass
{
public static void main(String[] args)
{
//Constructing An ArrayList
ArrayList<String> listWithDuplicateElements = new ArrayList<String>();
listWithDuplicateElements.add("JAVA");
listWithDuplicateElements.add("J2EE");
listWithDuplicateElements.add("JSP");
listWithDuplicateElements.add("SERVLETS");
listWithDuplicateElements.add("JAVA");
listWithDuplicateElements.add("STRUTS");
listWithDuplicateElements.add("JSP");
//Printing listWithDuplicateElements
System.out.print("ArrayList With Duplicate Elements :");
System.out.println(listWithDuplicateElements);
//Constructing HashSet using listWithDuplicateElements
HashSet<String> set = new HashSet<String>(listWithDuplicateElements);
//Constructing listWithoutDuplicateElements using set
ArrayList<String> listWithoutDuplicateElements = new ArrayList<String>(set);
//Printing listWithoutDuplicateElements
System.out.print("ArrayList After Removing Duplicate Elements :");
System.out.println(listWithoutDuplicateElements);
}
}
评论10