Java Program to Find Frequency of Elements in Array
HashMap in Java to count frequencies by iterating the array and updating counts with map.put(element, map.getOrDefault(element, 0) + 1).Examples
How to Think About It
Algorithm
Code
import java.util.HashMap; import java.util.Map; public class FrequencyCounter { public static void main(String[] args) { int[] arr = {1, 2, 2, 3, 3, 3}; Map<Integer, Integer> freqMap = new HashMap<>(); for (int num : arr) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } System.out.println(freqMap); } }
Dry Run
Let's trace the array [1, 2, 2, 3, 3, 3] through the code
Start with empty map
{}
Process element 1
Map updates to {1=1}
Process element 2
Map updates to {1=1, 2=1}
Process element 2 again
Map updates to {1=1, 2=2}
Process element 3
Map updates to {1=1, 2=2, 3=1}
Process element 3 again
Map updates to {1=1, 2=2, 3=2}
Process element 3 again
Map updates to {1=1, 2=2, 3=3}
| Element Processed | Frequency Map |
|---|---|
| 1 | {1=1} |
| 2 | {1=1, 2=1} |
| 2 | {1=1, 2=2} |
| 3 | {1=1, 2=2, 3=1} |
| 3 | {1=1, 2=2, 3=2} |
| 3 | {1=1, 2=2, 3=3} |
Why This Works
Step 1: Use a map to store counts
A HashMap lets us link each number to how many times it appears.
Step 2: Update counts while looping
For each number, we check if it is already counted and add 1 to its count using getOrDefault.
Step 3: Print the final frequency map
After the loop, the map holds all numbers with their counts, which we print.
Alternative Approaches
public class FrequencyCounterNested { public static void main(String[] args) { int[] arr = {1, 2, 2, 3, 3, 3}; boolean[] counted = new boolean[arr.length]; for (int i = 0; i < arr.length; i++) { if (!counted[i]) { int count = 1; for (int j = i + 1; j < arr.length; j++) { if (arr[i] == arr[j]) { count++; counted[j] = true; } } System.out.println(arr[i] + " = " + count); } } } }
import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; public class FrequencyCounterStream { public static void main(String[] args) { int[] arr = {1, 2, 2, 3, 3, 3}; Map<Integer, Long> freqMap = Arrays.stream(arr) .boxed() .collect(Collectors.groupingBy(e -> e, Collectors.counting())); System.out.println(freqMap); } }
Complexity: O(n) time, O(n) space
Time Complexity
The program loops through the array once, so time grows linearly with input size.
Space Complexity
Extra space is needed for the map to store counts, which can be up to the size of the array if all elements are unique.
Which Approach is Fastest?
Using a HashMap is fastest (O(n)) compared to nested loops (O(n²)). Streams offer concise code but similar time complexity to HashMap.
| Approach | Time | Space | Best For |
|---|---|---|---|
| HashMap Counting | O(n) | O(n) | Large arrays, fast counting |
| Nested Loops | O(n²) | O(n) | Small arrays, no extra data structures |
| Java Streams | O(n) | O(n) | Concise code, Java 8+ environments |
HashMap.getOrDefault(key, 0) + 1 to simplify frequency counting.