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