Simplest way to find duplicate entries in an array is to add array entries to the TreeSet. As treeset does not support duplicate entries, we can easily find out duplicate entries.
Example
package com.w3spoint;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
//Create String Array
String[] strArray = {"Jai", "Mahesh", "Hemant", "Hemant", "Mahesh"};
//Create TreeSet Object
TreeSet<String> treeSet = new TreeSet<String>();
System.out.println("Duplicate Entries: ");
for(String string:strArray){
if(!treeSet.add(string)){
System.out.println(string);
}
}
}
} |
package com.w3spoint; import java.util.TreeSet; public class Test {
public static void main(String[] args) {
//Create String Array
String[] strArray = {"Jai", "Mahesh", "Hemant", "Hemant", "Mahesh"};
//Create TreeSet Object
TreeSet<String> treeSet = new TreeSet<String>();
System.out.println("Duplicate Entries: ");
for(String string:strArray){
if(!treeSet.add(string)){
System.out.println(string);
}
}
}
}
Output
Duplicate Entries:
Hemant
Mahesh |
Duplicate Entries:
Hemant
Mahesh