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:
- Creating ArrayList using nCopies method of Collections class
- How to get size or length of an ArrayList
- Adding element to ArrayList at specified index position
- Remove element from ArrayList at specified index position
- How to delete a element and delete all elements of an ArrayList
- How to get sublist from ArrayList
- How to check whether particular element is present in ArrayList
- Comparing two ArrayList objects using containsAll() method
- Adding one ArrayList to another ArrayList using addAll() method
- Replacing ArrayList element with new value using set() method
- How to get maximum element from ArrayList
- How to get minimum element from ArrayList
- Various ways to iterate through ArrayList
- How to reverse ArrayList contents
- Sorting ArrayList in descending order
- Sorting ArrayList using sort() method of List in Java 8
- Sorting list of objects on multiple fields using Comparator in Java
- Remove duplicate elements from ArrayList in Java
- How to remove duplicate elements of ArrayList maintaining insertion order
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/7/docs/api/java/util/List.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Happy Coding !!
Happy Learning !!