11 July, 2019

Find the duplicate strings in a list

In this article, we will see how to find the duplicate strings and their counts from an array or list using java.  This is one of important programming questions in technical interview. In this program we have used Map and List both, so its a kind of collections interview questions. You can find few more collection interview question.  Today we will see Find the duplicate strings in a list. 


The logic is very simple here, see the below.

  • At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
  • Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
  • Finally we will have the map , which holds the array elements with the counter for repentance. 
  • Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).

CountDuplicate.java

package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
 * This program illustrate how to find the number of duplicate Strings in a
 * List. Also, we can find the number of repeat for each duplicate String.
 *
 * @author manoj.bardhan
 *
 */
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 String - 3

1 comment: