Write a java program to check whether an array contains duplicates or not?

In this tutorial we will write a program to check whether an array contains duplicates.First we will write steps how to solve this then we will write a program.

Steps to check whether array contains duplicates or not

1)  create and initialize input array.

2)  Convert the array to list.

3)  Create an hashset using list.

4)  If list size and set size are not equal then we can say array contains duplicates.(Because set does not allow duplicates).

Java Example to check array contains duplicates or not

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

public class ArrayDuplicatesDemo {

	public static void main(String[] args) {

		String [] duplicates=new String[]{"java","oracle","c","java"};
		List duplicatesList=Arrays.asList(duplicates);
		Set duplicatesSet=new HashSet<>(duplicatesList);
		if(duplicatesList.size()!=duplicatesSet.size()){
			System.out.println("The array contains duplicates");
		}else{
			System.out.println("The array doesn't contains duplicates");
		}

	}

}

 Output:

The array contains duplicates

Leave a Reply

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