-1

I want to count strings that are repeated more than one in String Array in java. One way is to find string like that

String[] Array=new String[10];
String find;
System.out.print("Enter Strings for Array: ");

for(int i=0;i<Array.length;i++ ) {
    Array[i]=input.next();
}

System.out.print("Enter String to find");
find=input.next();

for(int i=0;i<Array.length;i++) {
    if(find.equals(Array[i]) {
        System.out.print("Found!");
    else
        System.out.print("Not Found!");
    }
}

But i want to search repeated strings through a loop and find repeated strings itself without getting input from user to find.

Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43
  • Possible duplicate of [Java Array, Finding Duplicates](http://stackoverflow.com/questions/3951547/java-array-finding-duplicates) – Chris Kitching Mar 12 '16 at 09:00

1 Answers1

0

First issue, you code won't compile. You open a block for your if statement, but don't close it before your else statement.

Based on your post, it seems like you want the counts of words in an array. Yet, your code suggests that you are trying to find if a string exists in an array. I'll guess it's the former, and proceed. Instead of an O(n*n) approach, the can be done in O(n) using a Map.

String[] arr = {"ab","c","d","e","ab"};
Map<String, Integer> map = new HashMap<String, Integer>();

for(String word: arr) {
    // if word is not in the map
    if(!map.containsKey(word))
        map.put(word, 0);
    map.put(word, map.get(word) + 1);
}

for(String word: map.keySet()) 
    System.out.println(word + " occurs " + map.get(word) + " times");
Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43