0
0
JavaProgramBeginner · 2 min read

Java Program to Find Frequency of Elements in Array

Use a HashMap in Java to count frequencies by iterating the array and updating counts with map.put(element, map.getOrDefault(element, 0) + 1).
📋

Examples

Input[1, 2, 2, 3, 3, 3]
Output{1=1, 2=2, 3=3}
Input[5, 5, 5, 5]
Output{5=4}
Input[]
Output{}
🧠

How to Think About It

To find how many times each number appears, go through each element one by one. Keep a record (like a list of counts) for each number you see. If the number is new, start its count at 1. If you see it again, add 1 to its count. At the end, you have the frequency of every number.
📐

Algorithm

1
Create an empty map to store element frequencies.
2
For each element in the array, check if it is already in the map.
3
If yes, increase its count by 1; if no, add it with count 1.
4
After processing all elements, return or print the map with frequencies.
💻

Code

java
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);
    }
}
Output
{1=1, 2=2, 3=3}
🔍

Dry Run

Let's trace the array [1, 2, 2, 3, 3, 3] through the code

1

Start with empty map

{}

2

Process element 1

Map updates to {1=1}

3

Process element 2

Map updates to {1=1, 2=1}

4

Process element 2 again

Map updates to {1=1, 2=2}

5

Process element 3

Map updates to {1=1, 2=2, 3=1}

6

Process element 3 again

Map updates to {1=1, 2=2, 3=2}

7

Process element 3 again

Map updates to {1=1, 2=2, 3=3}

Element ProcessedFrequency 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

Using two nested loops
java
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);
            }
        }
    }
}
This method uses no extra map but is slower (O(n²)) and less efficient for large arrays.
Using Java 8 Streams
java
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);
    }
}
This uses modern Java streams for concise code but requires Java 8+ and may be less clear for beginners.

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.

ApproachTimeSpaceBest For
HashMap CountingO(n)O(n)Large arrays, fast counting
Nested LoopsO(n²)O(n)Small arrays, no extra data structures
Java StreamsO(n)O(n)Concise code, Java 8+ environments
💡
Use HashMap.getOrDefault(key, 0) + 1 to simplify frequency counting.
⚠️
Beginners often forget to initialize counts or overwrite counts instead of incrementing them.