In this java example will learn how to check duplicated value in an array.
We can achieve it by two ways
- Using two for loop to compare each values in array
- Using HashSet to detect duplicated value
import java.util.Set;
import java.util.HashSet;
public class CheckDuplicate
{
public static void main(String args[])
{
String [] sValue = new String[]{"1","2","3","5","5","8","9","8"};
checkDuplicated_withNormal(sValue);
checkDuplicated_withSet(sValue);
}
//check duplicated value
private static boolean checkDuplicated_withNormal(String[] sValueTemp)
{
System.out.println("Check Normal : Value duplicated! \n");
for (int i = 0; i < sValueTemp.length; i++) {
String sValueToCheck = sValueTemp[i];
if(sValueToCheck==null || sValueToCheck.equals(""))continue; //empty ignore
for (int j = 0; j < sValueTemp.length; j++) {
if(i==j)continue; //same line ignore
String sValueToCompare = sValueTemp[j];
if (sValueToCheck.equals(sValueToCompare)){
System.out.println("Duplicate value "+sValueToCheck);
//return true;
}
}
}
return false;
}
//check duplicated value
private static boolean checkDuplicated_withSet(String[] sValueTemp)
{
System.out.println("Check Set : Value duplicated! \n");
Set sValueSet = new HashSet();
for(String tempValueSet : sValueTemp)
{
if (sValueSet.contains(tempValueSet))
{
System.out.println("Duplicate value "+tempValueSet);
}
else
if(!tempValueSet.equals(""))
sValueSet.add(tempValueSet);
}
return false;
}
}
|
Output:
Check Normal : Value duplicated!
Duplicate value 5
Duplicate value 5
Duplicate value 8
Duplicate value 8
Check Set : Value duplicated!
Duplicate value 5
Duplicate value 8
|