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

相關文章
相關標籤/搜索