In this article, we will see how to find duplicate strings and their counts from an array or a list using Java. This is one of the common programming questions asked in technical interviews.
In this program, we will use both Map and List, so it is also a good example for understanding Java Collections. You can find a few more Java Collection interview questions.
Today, we will see how to find duplicate strings in a list and count how many times each string is repeated.
Logic
The logic is quite simple:
First, we create a Map to store the key-value pair. The key will be the array element, and the value will be the number of times that element occurs.
Then, we iterate through the array or list and add each element to the Map. If the element is already present in the Map, we increase its count by 1.
After completing the iteration, the Map will contain each string along with the number of times it occurs.
Finally, we iterate through the Map and check for entries where the count is greater than 1. These are the duplicate or repeated strings.
CountDuplicate.java
package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class CountDuplicate {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(
Arrays.asList("JDG", "AA", "AA", "JAVA", "JavaScript", "Java", "Stream", "hibernate", "Hibernate"));
System.out.println("Input List = " + list);
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < list.size(); i++) {
if (map.isEmpty()) {
map.put(list.get(i).toUpperCase(), 1);
} else if (map.containsKey(list.get(i).toUpperCase())) {
map.put(list.get(i).toUpperCase(), map.get(list.get(i).toUpperCase()) + 1);
} else {
map.put(list.get(i).toUpperCase(), 1);
}
}
int counter = 0;
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
counter++;
System.out.println("String Found " + entry.getKey() + " with count " + entry.getValue());
}
}
System.out.println("Total Duplicate String - " + counter);
}
}
Output
Input List = [JDG, AA, AA, JAVA, JavaScript, Java, Stream, hibernate, Hibernate] String Found: AA with count 2 String Found: JAVA with count 2 String Found: HIBERNATE with count 2 Total Duplicate Strings: 3
Happy Learning!