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


11059 просмотра

7 ответа

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

I have tried while, for loops but the logic seems impossible.

Автор: thecodefather Источник Размещён: 13.11.2019 11:31

Ответы (7)

2 плюса


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+" ");

or something similar...

Автор: javajavajava Размещён: 14.06.2012 08:02

9 плюса

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.


for (int i = 0; i < array.length; ++i){
    if (i+1 == array.length) {
    } else if (array[i].equals(array[i+1])) {
        System.out.print(array[i]+" ");
    } else {
Автор: Hans Z Размещён: 14.06.2012 08:11

2 плюса

There are multiple ways of achieving this.

  1. Use two for loops, one that loops through the array and picks a value and another inner loop where you go through the array (from the current index) looking for that value
  2. You could have a map that contains the words, you loop through the array and you fill out the map with the number of occurrences corresponding to the value currently fetched from the array

The second way is better. The code is something like:

Map<String, Integer> occurences = new HashMap<String, Integer>();
for(int index=0; index < array.length; index++){
       int nOcc = 1;
         nOcc = occurences.get(array[index]) + 1;
       occurences.put(array[index], nOcc);

At this point, the map should contain all words (keys) and their corresponding number of occurrences (values)

Автор: GETah Размещён: 14.06.2012 07:57

1 плюс

If you sort the array first, then you can just check if the current index is equal to the next index (bearing in mind that you must account for IndexOutOfBounds), if they are equal do a System.out.print() if they are not equal do a System.Out.println().

String [] array = {"anps", "anps", "anps", "bbo", "ehllo"};
// If you already are assured that the strings in the array are sorted
// then the sort is not necessary. 
for(int i = 0; i < array.length; i++){
    if((i+1)==array.length || !array[i].equals(array[(i+1)])){
    } else {
        System.out.print(array[i]+" ");
Автор: NominSim Размещён: 14.06.2012 07:56

0 плюса

Complexity n^2 , just start from first value and go to the end finding the same, if you found print in one line and go to the new line, also you should delete all printed value.

Complexity nlogn + n == nlogn , merge or quick sort, and after this go to the end and pring sequenced values. There are more solutions but I think its enough for you.

Автор: Sergii Zagriichuk Размещён: 14.06.2012 07:59

0 плюса

Naive Algorithms

  • Create a Map
  • Iterate through all array
  • check if key already exist in map
  • if yes update value +1
  • if no insert
  • print the map as you want

You should be able to do what you're looking for !

Автор: Jean-Christophe Fortin Размещён: 14.06.2012 08:03

0 плюса

Use below logic

import java.util.ArrayList;

public class RepeatStringPrint {

     * @param args
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String[] x = { "anps", "anps", "anps", "bbo", "ehllo" };
            String total[] = new String[50];
            String sTotal[] = null;
            for (int i = 0; i < x.length; i++) {
                total[i] = x[i];
            for (int k = 0; k < total.length; k++) {
                int count = 0;
                if (total[k] != null) {
                    sTotal = new String[50];
                    for (int i = 0; i < total.length; i++) {
                        if (total[k] == total[i]) {
                            if (count <= 1) {
                                sTotal[i] = total[k];
                    if (sTotal[k] != null) {
                        for(int j=0; j<count; j++){

        catch (Exception e) {


Автор: Anil Patile Размещён: 12.07.2014 05:19
Вопросы из категории :