0

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]);
          } 
       }  
           }
    }


}
5
  • 1
    Did you try adding them to a set?. It is more efficient than your current approach which takes` O(n^2)` Commented Jun 11, 2015 at 6:17
  • I don't want to use set. Can you help me to know where is the error in code ? Commented Jun 11, 2015 at 6:19
  • Look at this stackoverflow.com/a/1937083/1737819. From the map of words with their occurrences choose those that have occurencies > 1. :) Commented Jun 11, 2015 at 6:24
  • 1
    What will happen when i=1 and j=1? How can you prevent i and j from having the same value, and comparing one word to itself? Commented Jun 11, 2015 at 6:32
  • 1
    first for has an error for(int i=0 ; i<**=**len;i++){. Can you spot it? Commented Jun 11, 2015 at 6:47

9 Answers 9

3
    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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Can i get number counts as well?
@Littlebird - For that you will have to use a Map / array to keep count
0

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]); 

Comments

0

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!

Comments

0

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

Comments

0

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() };    

Comments

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.