VOOZH about

URL: https://www.geeksforgeeks.org/java/count-occurrences-elements-list-java/

⇱ Count occurrences of elements of list in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count occurrences of elements of list in Java

Last Updated : 11 Jul, 2025

Suppose we have an elements in ArrayList, we can count the occurrences of elements present in a number of ways.

This data structure uses hash function to map similar values, known as keys to their associated values. Map values can be retrieved using key as it contains key-value pairs. 

Output:
Element Geeks occurs: 2 times
Element for occurs: 1 times

This data structure does not allow duplicate elements as it implements Set Interface. Objects are inserted based on their hash code. To count occurrences of elements of ArrayList, we create HashSet and add all the elements of ArrayList. We use Collections.frequency(Collection c, Object o) to count the occurrence of object o in the collection c. Below program illustrate the working of HashSet: Program to find occurrence of words 

Output:
Geeks: 2
for: 1

This data structure stores unique elements in sorted order. It uses the concept of red-black-tree in the background to prevent duplicates. 

Output:
Frequency of Geeks is 2
Frequency of for is 1

Key Points:

  • HashMap implements Map Interface while TreeMap implements SortedMap Interface.
  • HashMap uses Hashing whereas TreeMap uses Red-Black Tree(Balanced BST). So HashMap based solutions are generally much faster than TreeMap based solutions.
Comment