Find the duplicate and unique values in an array in Java
Description
The following code shows how to find the duplicate and unique values in an array.
Example
//from ww w . j a v a 2 s .c o m
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> uniques = new HashSet<String>();
Set<String> dups = new HashSet<String>();
String[] data = new String[]{"java2s.com","a","v","c","d","java2s.com",};
for (String a : data){
if (!uniques.add(a)){
dups.add(a);
}
}
uniques.removeAll(dups);
System.out.println("Unique words: " + uniques);
System.out.println("Duplicate words: " + dups);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »