Java删除Arr
方法1:使用HashSet删除ArrayList中重复的元素
import java.util.ArrayList;import java.util.HashSet;public static void mpublic class MainClass{
ain(String[] args) {ArrayList ArrayList<String//Constructing An
> listWithDuplicateElements = new ArrayList<String>();istWithDuplicateElements.add("J2EE");listWithDuplicateElements.add("JAVA");
l listWithDuplicateElements.add("JSP"); listWithDuplicateElements.add("SERVLETS");"); listWithDuplicateElements.add("JSlistWithDuplicateElements.add("JAVA"); listWithDuplicateElements.add("STRUT
SP"); //Printing listWithDuplicateElements System.out.print("ArrayList With Duplicate Elements :");HashSet<String> set = new HashSet<String>(lisSystem.out.println(listWithDuplicateElements); //Constructing HashSet using listWithDuplicateElementstWithDuplicateElements);); //Printing listWithoutDuplicateElements//Constructing listWithoutDuplicateElements using set ArrayList<String> listWithoutDuplicateElements = new ArrayList<String>(se
tSystem.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]
方法2:使用LinkedHashSet删除ArrayList中重复的元素
import java.util.ArrayList;import java.util.LinkedHashSet;public class MainClass{n(String[] args) { //Constructpublic static void ma
iing An ArrayListtring> listWithDuplicateElements = new ArrayList<String>(); listWithDArrayList<
SuplicateElements.add("JAVA"); listWithDuplicateElements.add("J2EE");.add("SERVLETS"); listWithDuplicateElistWithDuplicateElements.add("JSP"); listWithDuplicateElement
slements.add("JAVA"); listWithDuplicateElements.add("STRUTS"); listWithDuplicateElements.add("JSP");System.out.println(listWithDuplicateElements//Printing listWithDuplicateElements System.out.print("ArrayList With Duplicate Elements :");
); //Constructing LinkedHashSet using listWithDuplicateElements LinkedHashSet<String> set = new LinkedHashSet<String>(listWithDuplicateElements);
//Constructing listWithoutDuplicateElements using set ArrayList<String> listWithoutDuplicateElements = new ArrayList<String>(set); //Prin
ting 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中的重复元素后,依然保持了元素的插入顺序。
译文链接:http://www.codeceo.com/article/java-arraylist-remove-duplicate-ele.html
英文原文:How To Remove Duplicate Elements From ArrayList In Java?
ayList中的重复元素的2种方法