Find Duplicate Strings in an Array

In this article, we will learn how to write a Java program to identify and count duplicate strings in an array. This is a common problem that tests your understanding of arrays and hash-based data structures in Java.

Problem Statement:

We are given an array of strings, and the task is to find duplicate strings and count their occurrences. The output will display each duplicate string along with the number of times it appears in the array.

Approach to Solve the Problem

  1. Use a HashMap:
    • Store each string as a key in the map.
    • Increment the value associated with the key every time the string appears.
  2. Identify Duplicates: After populating the map, check for keys with values greater than 1.
  3. Display Results: Print the duplicate strings along with their counts.

Java program to find duplicate strings in an Array

This program provides a simple and efficient way to identify and count duplicate strings in an array. It highlights key Java concepts such as hash-based data structures and string processing.

package com.javacodepoint.stringarray;

import java.util.HashMap;

public class DuplicateStringFinder {
	public static void main(String[] args) {
		// Input array of strings
		String[] words = { "apple", "banana", "apple", "orange", "banana", "apple" };

		// Call the method to find duplicates
		findDuplicates(words);
	}

	// Method to find and count duplicate strings in an array
	public static void findDuplicates(String[] words) {
		HashMap<String, Integer> wordCountMap = new HashMap<>();

		// Populate the HashMap with word counts
		for (String word : words) {
			wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
		}

		// Identify and display duplicates
		for (String word : wordCountMap.keySet()) {
			int count = wordCountMap.get(word);
			if (count > 1) {
				System.out.println("Duplicate string \"" + word + "\" appears " + count + " times.");
			}
		}
	}
}

OUTPUT:

Duplicate string “banana” appears 2 times.
Duplicate string “apple” appears 3 times.

Code Explanation:

  1. Input Array: The array words contains the strings for which duplicates need to be identified.
  2. HashMap for Counting:
    • A HashMap is used to store each string as a key and its occurrence count as the value.
    • The getOrDefault method simplifies updating the count for each string.
  3. Finding Duplicates:
    • After populating the map, a for-each loop iterates through the keys.
    • Strings with a count greater than 1 are identified as duplicates and printed.

You can learn the Top 20 string array programs for interview preparation (Click here).

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *