How to find duplicate elements in a List

How to find duplicate elements in a List

Problem statement

Write a program to find duplicate elements in a List.

We suggest you think about a solution before reading further…


Loop through each element in the List and insert each element HashSet class. We will get false for every element which is duplicate while inserting into the HashSet class.

package com.core2succeed.list;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateElementInList {
	public static void main(String[] args) {
		List companyNames = Arrays.asList("google", "yahoo", "bankofamerica", "ebay", "google", "nike", "ebay");
		System.out.println("Original list containing company names : "+companyNames);
		Set dublicateNames = dublicateElement(companyNames);
		System.out.println("DuplicateNames : "+dublicateNames);
	public static Set dublicateElement(List companyNames) {
		Set set = new HashSet();
		Set dublicateNames = new HashSet();
		for(String companyName: companyNames) {
			if(!set.add(companyName)) {
		return dublicateNames;


Original list containing company names : [google, yahoo, bankofamerica, ebay, google, nike, ebay]
DuplicateNames : [google, ebay]



Leave a Reply

Your email address will not be published. Required fields are marked *