I found two way to find the duplicate value from string array.
First way :
private static String FindDupValue(String[] sValueTemp) {
    for (int i = 0; i < sValueTemp.length; i++) {
      String sValueToCheck = sValueTemp[i];
      if(sValueToCheck==null || sValueToCheck.equals(""))continue;
      for (int j = 0; j < sValueTemp.length; j++) {
        if(i==j)continue;
        String sValueToCompare = sValueTemp[j];
        if (sValueToCheck.equals(sValueToCompare)){
          return sValueToCompare;
        }
      }
    }
    return "";
  }
Second way :
private static String FindDupValueUsingSet(String[] sValueTemp) {
    Set<String> sValueSet = new HashSet<String>();
    for(String tempValueSet : sValueTemp) {
      if (sValueSet.contains(tempValueSet))
        return tempValueSet;
      else
        if(!tempValueSet.equals(""))
          sValueSet.add(tempValueSet);
    }
    return "";
  }
Both methods are correct.
My question is which one best method and why? Or is there any other best way to find out duplicate value form an array?
function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }
Nice thing about Set is that it's add operation returns
true if this set did not already contain the specified element.
public static void main(String[] args) {
    Set<String> set = new HashSet<>();
    String[] stringsToTest = {"a", "b", "c", "a"};
    for (String s : stringsToTest) {
        boolean notInSetYet = set.add(s);
        if (!notInSetYet) {
            System.out.println("Duplicate: " + s);
        }
    }
}
Output:
Duplicate: a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With