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.
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With