Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicate value from string array [duplicate]

Tags:

java

arrays

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?

like image 208
Shiladittya Chakraborty Avatar asked Dec 25 '15 12:12

Shiladittya Chakraborty


People also ask

How do you find duplicate values in 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. }


1 Answers

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

like image 199
Zakhar Avatar answered Oct 05 '22 19:10

Zakhar