Little bird
Little bird

Reputation: 1088

How to find a duplicate string in a string array

I have the following code where i want to retrieve only those values which are duplicate but could not find the right result.I don't know where i'm wrong.

public class TestDummy {
    public static void main(String args[]){
       String arr[] ={"lady", "bird", "is","bird","lady","cook"};
       int len = arr.length;
       System.out.println("Size "+len);
       for(int i=0 ; i<=len;i++){
           for(int j=1 ; j< len-1;j++){
            if(arr[i]==arr[j]){
              System.out.println("Duplicate "+arr[i]);
          } 
       }  
           }
    }


}

Upvotes: 0

Views: 133

Answers (9)

Asheesh Kumar
Asheesh Kumar

Reputation: 161

above solutions does work
but just to make code clean you could use Linq.js

Upvotes: 0

Mehdi
Mehdi

Reputation: 3763

public static String[] removeDuplicates(String[] array){                                           
    return new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);       
}                                                                                   

Upvotes: 0

Create a Map of your words and occurencies.

import java.util.*;

public class TestDummy {
    public static void main(String args[]) {
        String arr[] = {
            "lady", "bird", "is", "bird", "lady", "cook"
        };
        Map<String, Integer> dictionary = new TreeMap<>();

        int len = arr.length;
        System.out.println("Size " + len);
        for (int i = 0; i < len; i++) {
            if (dictionary.containsKey(arr[i])) {
                dictionary.put(arr[i], dictionary.get(arr[i]) + 1);
                System.out.format("Duplicate %s%n", arr[i]);
            } else {
                dictionary.put(arr[i], 1);
            }
        }
    }
}



**Output**
    Size 6
    Duplicate bird
    Duplicate lady

Upvotes: 0

Peter Pan
Peter Pan

Reputation: 24128

    String arr[] ={"lady", "bird", "is","bird","lady","cook"};
    Map<String, Integer> map = new HashMap<>();
    for(String str: arr) {
        if(map.containsKey(str)) {
            map.put(str, map.get(str)+1);
        } else{
            map.put(str, 1);
        }
    }
    for(String str: map.keySet()) {
        if(map.get(str) > 1) {
            System.out.println("Duplicate: "+ str+" count:"+map.get(str));
        }
    }

output:

Duplicate: bird count:2
Duplicate: lady count:2

Upvotes: 3

GreenEyedAndy
GreenEyedAndy

Reputation: 1525

This gives you a list with the duplicates and their count:

var duplicates =
from word in arr
group word by word into g
where g.Count() > 1
select new { g.Key, Count = g.Count() };    

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

You have to change your code to :

public static void main(String args[]) {
        String arr[] = { "lady", "bird", "is", "bird", "lady", "cook" };
        int len = arr.length;
        System.out.println("Size " + len);
        for (int i = 0; i < len; i++) { // not <= but only <
            for (int j = i + 1; j < len; j++) {  // start from i+1 and go upto last element
                if (arr[i].equals(arr[j])) { // use equals()
                    System.out.println("Duplicate " + arr[i]);
                }
            }
        }
    }

O/P :

Size 6
Duplicate lady
Duplicate bird

Upvotes: 1

Codebender
Codebender

Reputation: 14471

There are a few issues.

   for(int i=0 ; i<len;i++){
       for(int j=i +1 ; j< len;j++){
        if(arr[i].equals(arr[j])){
          System.out.println("Duplicate "+arr[i]);
      } 
   }  
       }

Note that: I have change j=1 to j=i and == to .equals and <= to < and len -1 to len

Upvotes: 0

Vihar
Vihar

Reputation: 3831

you can use a simpler approach like the following

Set<String> strings=new Hashset<String>();
for(int i=0;i<len;i++){
    if(strings.add(arr[i])==false){
        System.out.println(arr[i]+" is a duplicate");
    }
}

and in your existing code do it like arr[i].equals(arr[j]) to see if values are equal(if they are equal they are duplicate)

== checks for reference equivalence, while equals() method checks for value equivalence, so you should be using equals method whenever you need to check equivalence of two objects

hope it helps!

Good luck!

Upvotes: 0

Uma Kanth
Uma Kanth

Reputation: 5629

Firsty Strings are to be compared with .equals() not ==

if(arr[i].equals(arr[j]))
{
   System.out.println("Duplicate "+arr[i]);
}

And I would recommend you to use sets as they dont allow duplicate values to be entered into it, or a list and check if it already exists using a .contains() method.

List<String> list = new ArrayList();

for(int i = 0; i < arr.length; i++)
   if(list.contains(arr[i])
     System.out.println("Duplicate" + arr[i]);
   else
     list.add(arr[i]); 

Upvotes: 0

Related Questions