Detect Duplicates using Set

We can Easily Detect Duplicates using Set. In this tutorial we will create a program whose functionality will be to detect duplicates using set in the given input. in the program we are using Set because set does not contain duplicate elements.

code to detect duplicates using set:-

import java.util.HashSet;
import java.util.Set;

public class FindDuplicates {
	
 public static void main(String args[]) {
	 
  Set<String> s = new HashSet<String>();
  
  for (int i=0; i<args.length; i++){
	  
     if (!s.add(args[i])){ 
    	 System.out.println("duplicate-detected: " + args[i]);
     }
    }
    System.out.println(s.size()+" distinct-words-detected: "+s);
  }
}

compile this class using command javac FindDuplicates.java
run this class using command java FindDuplicates i came i saw i left

output:-
detect duplicates using set

in the above program we are taking input using command line arguments, creating an object of HashSet. We select set because set does not contain duplicate elements. while Adding the elements to the HashSet, the hashSet will return true if it does not contain that element otherwise false.

Leave a Comment