当前位置: 首页 > 科技观察

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

时间:2023-03-16 15:42:47 科技观察

ArrayList是Java中最常用的集合类型之一。它允许灵活地添加多个空元素、复制元素和维护元素的插入顺序。我们在编码的时候,经常会遇到构建的ArrayList必须去除重复元素的需求。本文将给出两种从ArrayList中删除重复元素的方法。方法一:使用HashSet删除ArrayList中的重复元素在该方法中,我们使用HashSet删除重复元素。如您所知,HashSet不允许重复元素。我们使用HashSet的这个属性来删除构建的ArrayList中的重复元素。然而,这种方法有一个缺点。也就是说,它删除了ArrayList中元素的插入顺序。这意味着在去除重复元素后,元素的插入顺序是乱序的。我们先来看下面的例子。importjava.util.ArrayList;importjava.util.HashSet;publicclassMainClass{publicstaticvoidmain(String[]args){//构造一个ArrayListArrayListlistWithDuplicateElements=newArrayList();listWithDuplicateElements.add("JAVA");listWithDuplicateElements.add("J2EE");listWithDuplicateElements.add("JSP");listWithDuplicateElements.add("SERVLETS");listWithDuplicateElements.add("JAVA");listWithDuplicateElements.add("STRUTS");listWithDuplicateElements.add("JSP");//打印listWithDuplicateElementsSystem.out.print("ArrayListWithDuplicateElements:");System.out.println(listWithDuplicateElements);//使用listWithDuplicateElements构造HashSetHashSetset=newHashSet(listWithDuplicateElements);//使用setArrayListlistWithoutDuplicat构造listWithoutDuplicateElementseElements=newArrayList(set);//打印listWithoutDuplicateElementsSystem.out.print("ArrayListAfterRemovedDuplicateElements:");System.out.println(listWithoutDuplicateElements);}}输出:ArrayListWithDuplicateElements:[JAVA,J2EE,JSP,SERVLETS,JAVA,STRUTS,JSP]ArrayListAfterRemovedDuplicateElements:[JAVA,SERVLETS,JSP,J2EE,STRUTS]注意输出你会发现在删除重复元素后,元素被重新洗牌。不再按广告顺序排列。如果你想在删除重复元素后保持元素的插入顺序,不推荐使用这种方法。还有另一种方法可以确保即使在删除重复元素后元素的插入顺序也不会改变。那就是使用LinkedHashSet。方法二:使用LinkedHashSet删除ArrayList中的重复元素在该方法中,我们使用LinkedHashSet删除ArrayList中的重复元素。如您所知,LinkedHashSet在保持元素插入顺序的同时不允许出现重复元素。LinkedHashSet的这两个属性可以保证在删除ArrayList中的重复元素后保持元素的插入顺序。请参见下面的示例。importjava.util.ArrayList;importjava.util.LinkedHashSet;publicclassMainClass{publicstaticvoidmain(String[]args){//构造一个ArrayListArrayListlistWithDuplicateElements=newArrayList();listWithDuplicateElements.add("JAVA");listWithDuplicateElements.add("J2EE");listWithDuplicateElements.add("JSP");listWithDuplicateElements.add("SERVLETS");listWithDuplicateElements.add("JAVA");listWithDuplicateElements.add("STRUTS");listWithDuplicateElements.add("JSP");//打印listWithDuplicateElementsSystem.out.print("ArrayListWithDuplicateElements:");System.out.println(listWithDuplicateElements);//使用listWithDuplicateElements构造LinkedHashSetLinkedHashSetset=newLinkedHashSet(listWithDuplicateElements);//使用setArrayListlistWithoutDuplicateElements=newArrayList(set);//打印listWithoutDuplicateElementsSystem.out.print("ArrayListAfterRemovedDuplicateElements:");System.out.println(listWithoutDuplicateElements);}}输出:ArrayListWithDuplicateElements:[JAVA,J2EE,JSP,SERVLETS,JAVA,STRUTS,JSP]ArrayListAfterRemovedDuplicateElements:[JAVA,J2EE,JSP,SERVLETS,STRUTS]注意输出。可以发现删除ArrayList中的重复元素后,元素依然保持不变。插入顺序。翻译链接:http://www.codeceo.com/article/java-arraylist-remove-duplicate-ele.html英文原文:HowToRemoveDuplicateElementsfromArrayListInJava?