How can I count and print duplicate strings in a string array in Java?

java

Solution

Sort the array first then

for(int i = 0, i < array.length; i++){
    String temp = array[i];
    System.out.print(temp+" ");
    for(int j = i+1; j < array.length; j++){
        String temp2 = array[j];
        if(temp.compareTo(temp2) == 0){
            System.out.print(temp2+" ");
            i++;
        }
    }
    System.out.println();
}

or something similar...

Problem

I have a dilemma on my hands. After much trial and error, I still could not figure out this simple task. I have one array ``` String [] array = {anps, anps, anps, bbo, ehllo}; ``` I need to be able to go through the array and find duplicates and print them on the same line. Words with no duplicates should be displayed alone The output needs to be like this ``` anps anps anps bbo ehllo ``` I have tried while, for loops but the logic seems impossible.

Original source