Identify duplicate elements using HashSet and HashMap in Java

This program that you see is using HashSet and HashMap which is considered better than using 2 for loops to do the same job.

Using HashSet >> Stores unique values.

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

public class DuplicateElements {
  public static void main(String[] args) {
  String names[] = {"Java", "C", "C++", "Golang", "Ruby", "C"};
      Set<String> s = new HashSet<String>();
      for (String name : names) {
if (s.add(name) == false) {   System.out.println("Duplicate element:"+ name);
}
     }
   }
}

Using HashMap

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class DuplicateElements {

public static void main(String[] args) {
String names[] = {"Java", "C", "C++", "Golang", "Ruby", "C++"};
Map<String, Integer> s = new HashMap<String, Integer>();
for (String name: names) {
Integer count = s.get(name);
if (count == null) {
s.put(name, 1);
}
else {
s.put(name, ++count);
}
}
//get values from this HashMap
Set<Entry<String, Integer>> e = s.entrySet();
for (Entry<String, Integer> entry: e) {
if (entry.getValue()>1) {
System.out.println("Duplicate Item:" + entry.getKey());
}
}
}
}

No comments:

Post a Comment