ArrayList中重复元素处理方法.[Java]

java

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

private static void sortByHashSet() {

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

System.out.print("ArrayList With Duplicate Elements :");

System.out.println(listWithDuplicateElements);

HashSet<String> set = new HashSet<String>(listWithDuplicateElements);

ArrayList<String> listWithoutDuplicateElements = new ArrayList<String>(set);

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 :[SERVLETS, STRUTS, JSP, J2EE, JAVA]

使用HashSet删除ArrayList中重复的元素
注意输出结果。你会发现,在删除重复元素之后,元素重新洗牌。不再按照插入顺序排列

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

private static void sortByLinkedHashSet() {

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

System.out.print("ArrayList With Duplicate Elements :");

System.out.println(listWithDuplicateElements);

LinkedHashSet<String> set = new LinkedHashSet<String>(listWithDuplicateElements);

ArrayList<String> listWithoutDuplicateElements = new ArrayList<String>(set);

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]

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

英文原文连接 :http://javaconceptoftheday.com/how-to-remove-duplicate-elements-from-arraylist-in-java/

以上是 ArrayList中重复元素处理方法.[Java] 的全部内容, 来源链接: utcz.com/z/392700.html

回到顶部