Java ArrayList删除重复元素的2种方法

1. 使用HashSet删除ArrayList中重复的元素

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);  
}

输出:

ArrayList With Duplicate Elements :[JAVA, J2EE, JSP, SERVLETS, JAVA, STRUTS, JSP]
ArrayList After Removing Duplicate Elements :[JAVA, SERVLETS, JSP, J2EE, STRUTS]

注意输出结果。你会发现,在删除重复元素之后,元素重新洗牌。不再按照插入顺序排列。如果你想在删除重复的元素之后依然保持元素的插入顺序,那么不 建议使用此方法。还有另一种方法,可以保证在删除重复的元素之后也不改变元素的插入顺序。那就是使用LinkedHashSet。

2. 使用LinkedHashSet删除ArrayList中重复的元素

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 LinkedHashSet using listWithDuplicateElements  
 LinkedHashSet<String> set = new LinkedHashSet<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);  
} 

输出:
ArrayList With Duplicate Elements :[JAVA, J2EE, JSP, SERVLETS, JAVA, STRUTS, JSP]
ArrayList After Removing Duplicate Elements :[JAVA, J2EE, JSP, SERVLETS, STRUTS]

注意输出。你可以发现在删除ArrayList中的重复元素后,依然保持了元素的插入顺序。

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。