Java – How to count duplicate elements of ArrayList ?

In this article, we will count of number of duplicate elements present in List using Collections class’s utility frequency() method

1. Count duplicate elements from List:

Method signature:

public static int frequency(Collection c, Object o);

CountOfDuplicateElementsOfArrayList.java

package in.bench.resources.java.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class CountOfDuplicateElementsOfArrayList {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		// ArrayList contains duplicates and null
		al.add("Facebook");
		al.add("LinkedIn");
		al.add("YouTube");
		al.add(null);
		al.add("LinkedIn");
		al.add("Facebook");
		al.add("LinkedIn");
		al.add("YouTube");
		al.add("Facebook");
		al.add("Google");
		al.add(null);

		// create HashSet to find duplicate element
		HashSet<String> hsUnique = new HashSet<String>(al);

		System.out.println("Duplicates\tElement Name");
		System.out.println("==========\t=================");

		// Iterate using enhanced for-loop
		for (String strElement : hsUnique) {
			System.out.println(
					Collections.frequency(al, strElement)
					+ "\t\t"
					+ strElement);
		}
	}
}

Output:

Duplicates	Element Name
==========	=================
2			null
3			Facebook
3			LinkedIn
2			YouTube
1			Google

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to get synchronized version of List ?
Java - How to Reverse order of Comparator ?