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

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

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中重复的元素
注意输出结果。你会发现,在删除重复元素以后,元素从新洗牌。再也不按照插入顺序排列

 

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

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/code

相关文章
相关标签/搜索