Question: Brand new to Java and I cannot seem to figure this out: 

All I'm trying to do is print a duplicate string and the number of times it shows up in an array (not using hash tables or anything like that, just very simplistically). 

Let's say for an array like this: 

```
tempArray = {"dogs", "cats", "dogs", "dogs", "mice", "snakes", "cats"}

```

Here's my code thus far: 

```
int flowerCount = 0;
for (int j = 0; j < tempArray.length - 1; j++) {
        for (int k = j + 1; k < tempArray.length; k++) {
              if( (tempArray[j].equals(tempArray[k])) && (j != k) ) {
                    System.out.println(tempArray[j]);
                    flowerCount++;
               }

         }

 }

```

Obviously this doesn't work, what am I doing wrong here? This seems like it should be so simple to do, but I can't get the nested loops and counter right.

Answer: 
You can sort the array using `Arrays.sort`. This will put equal elements next to each other. Then you can simply iterate through the list with a while loop, looking for consecutive elements which are equal.

```
int i = 0;
while (i < arr.length) {
  int start = i;
  while (i < arr.length && arr[i].equals(arr[start])) {
    ++i;
  }
  int count = i - start;
  System.out.println(arr[start] + " " + count);
}

```
One easy way to count duplicates is to try to add them to a set. A set doesn't allow duplicates, so each time adding a string fails, it is because the string already exists in the set.

The `add()` method in a set returns a boolean, indicating if the add was successful or not. If the string you are trying to add is already in the set, the add will fail and the method will return false.

So something like:

```
HashSet<String> yourSet = new HashSet<>(); //Could be any kind of set, I'm just used to HashSets
int j = 0; j < tempArray.length - 1; j++) {
    if (yourSet.add(tempArray[j]) {
        //String was added succesfully, so it is not a duplicate.
    }  else {
        //String is duplicate.  Increment a duplicate counter for this string (and start at 2, if you want to include the initial occurence that is already in the set
    }
}

```