Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 521
xWAV92OdD445CbzcZAEyunk2M06fJi Avatar asked Dec 07 '22 14:12

xWAV92OdD445CbzcZAEyunk2M06fJi


1 Answers

Okay, there are a worryingly number of either wrong answers or answers that use HashMap or HashSet for this very simple iteration problem, so here is a correct solution.

Arrays.sort(array);

for (int i = 0; i < array.length; ++i){
    if (i+1 == array.length) {
        System.out.println(array[i]);
    } else if (array[i].equals(array[i+1])) {
        System.out.print(array[i]+" ");
    } else {
        System.out.println(array[i]);
    }
}
like image 144
Hans Z Avatar answered May 04 '23 00:05

Hans Z