如何从java中从ArrayList中删除重复项

时间:2020-02-23 14:34:22  来源:igfitidea点击:

在本教程中,我们将看到如何从Java中从ArrayList中删除重复元素。

有很多方法可以做到。
他们之中有一些是:

  • 使用迭代方法
  • 使用HashSet(但不保持插入顺序)
  • 使用linkedhashmap.

程序:

package org.igi.theitroad.algo;
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.*;
 
public class RemoveDuplicatesArrayListMain {
	/*
	 * @author : igi Mandliya
	 */
	public static void main(String[] args) {
		ArrayList employeeNameList = new ArrayList();
		employeeNameList.add("John");
		employeeNameList.add("Ankit");
		employeeNameList.add("Rohan");
		employeeNameList.add("John");
		employeeNameList.add("Amit");
		employeeNameList.add("Ankit");
 
		System.out.println("Removing duplicates from list:");
		//Using iterative approach
		ArrayList uniqueElements = new ArrayList();
		for (String empName : employeeNameList) {
 
			if (!uniqueElements.contains(empName)) {
				uniqueElements.add(empName);
			}
		}
 
		System.out.println("Using iterative approach:");
		for (String uniqElem : uniqueElements) {
			System.out.println(uniqElem);
		}
		System.out.println("***");
		System.out.println("Using HashSet :");
		//using HashSet but does not maintain order
		uniqueElements = new ArrayList(new HashSet(
				employeeNameList));
		for (String uniqElem : uniqueElements) {
			System.out.println(uniqElem);
		}
		System.out.println("***");
		System.out.println("Using LinkedHashSet :");
		//using LinkedHashSet maintaining order
		uniqueElements = new ArrayList(new LinkedHashSet(
				employeeNameList));
		for (String uniqElem : uniqueElements) {
			System.out.println(uniqElem);
		}
 
	}
}

运行上面的程序时,我们将获取以下输出:

Removing duplicates from list:
Using iterative approach:
John
Ankit
Rohan
Amit
***
Using HashSet :
Rohan
Ankit
Amit
John
***
Using LinkedHashSet :
John
Ankit
Rohan
Amit