How to find count of duplicates in a List


There are many different ways to find out the duplicates in a List or count of duplicates in a List object. Three best ways have been implemented in the below sample class. I suggest to go with 2nd sample, when there is a requirement in your project.

package in.javatutorials;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CountOfDuplicatesInList {

public static void main(String[] args) {

List<String> list = new ArrayList<String>();
list.add(“a”);
list.add(“b”);
list.add(“c”);
list.add(“d”);
list.add(“b”);
list.add(“c”);
list.add(“a”);
list.add(“a”);
list.add(“a”);

// Find out the count of duplicates by passing a String – static way
System.out.println(“\n Output 1 – Count ‘a’ with frequency”);
System.out.println(“a : ” + Collections.frequency(list, “a”));

// Find out the count of duplicates using Unique values – dynamic way
System.out.println(“\n Output 2 – Count all with frequency”);
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
System.out.println(temp + “: ” + Collections.frequency(list, temp));
}

// Find out the count of duplicates using Map – Lengthy process
System.out.println(“\n Output 3 – Count all with Map”);
Map<String, Integer> map = new HashMap<String, Integer>();

for (String temp : list) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(“Key : ” + entry.getKey() + ” Value : ”
+ entry.getValue());
}
}
}

 

Other Useful Links:

Avoid nested loops using Collection Framework in Java

Replace special characters in a String using java

Singleton Design pattern in JAVA

Convert Array to Vector in Java

How to Copy an Array into Another Array in Java

Tips to follow while doing java code