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.
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
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.
Frequency of Geeks is 2 Frequency of for is 1
- 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.
- Count occurrences of a given character using Regex in Java
- Java program to count the occurrences of each character
- Count minimum frequency elements in a linked list
- Remove elements from a List that satisfy given predicate in Java
- Pattern Occurrences : Stack Implementation Java
- Remove all occurrences of an element from Array in Java
- Count occurrences of a string that can be constructed from another given string
- Program to convert List of String to List of Integer in Java
- Program to convert List of Integer to List of String in Java
- Count elements present in first array but not in second
- Count all elements in the array which appears at least K times after their first occurrence
- Count frequencies of all elements in array in Python using collections module
- Find the difference of count of equal elements on the right and the left for each element
- Set to List in Java
- List to Set in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : mike00