Java - How to count duplicated items in a List

In this section, we will show you how to count duplicated items in a List,using Collections.frequency and Map.

Main.java

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;
import java.util.TreeMap;

public class Main {

public static void main(String[] args) {

List<String> list = new ArrayList<>();
list.add("Java");
list.add("Kotlin");
list.add("Python");
list.add("PHP");
list.add("Angular");
list.add("Java");
list.add("Kotlin");
list.add("React");
list.add("PHP");

System.out.println("\nExample 1 - Count 'Java' with frequency");
System.out.println("Java : " + Collections.frequency(list, "Java"));

System.out.println("\nExample 2 - Count all with frequency");
Set<String> uniqueSet = new HashSet<>(list);
for (String temp : uniqueSet) {
System.out.println(temp + ": " + Collections.frequency(list, temp));
}

System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<>();

for (String temp : list) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
printMap(map);

System.out.println("\nSorted Map");
Map<String, Integer> treeMap = new TreeMap<>(map);
printMap(treeMap);

}

public static void printMap(Map<String, Integer> map){

for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
}
}


Console Output:
Example 1 - Count 'Java' with frequency
a : 2

Example 2 - Count all with frequency
Java: 2
PHP: 2
React: 1
Angular: 1
Kotlin: 2
Python: 1

Example 3 - Count all with Map
Key : Java Value : 2
Key : PHP Value : 2
Key : React Value : 1
Key : Angular Value : 1
Key : Kotlin Value : 2
Key : Python Value : 1

Sorted Map
Key : Angular Value : 1
Key : Java Value : 2
Key : Kotlin Value : 2
Key : PHP Value : 2
Key : Python Value : 1
Key : React Value : 1


More topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete