Finding the frequency of each element in an array.
Hint: Suppose we have the following array of numbers: [2, 3, 4, 2, 5, 3, 4, 2, 3, 5, 5].
After iterating through the array, we will have a frequency map that looks like this:
{2=3, 3=3, 4=2, 5=3}
Therefore frequency of each element in an array is 3
Here’s an example Java program that finds the frequency of each element in an array:
import java.util.HashMap; import java.util.Map; public class FrequencyCounter { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 1, 5, 1}; Map<Integer, Integer> frequencyMap = new HashMap<>(); // Count the frequency of each element in the array for (int num : array) { if (frequencyMap.containsKey(num)) { frequencyMap.put(num, frequencyMap.get(num) + 1); } else { frequencyMap.put(num, 1); } } // Print the frequency of each element for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { System.out.println("Element " + entry.getKey() + " occurs " + entry.getValue() + " time(s)"); } } }
In this program, we use a `HashMap` to store the frequency of each element in the `array`. We iterate over each element in the array and update the frequency accordingly. Finally, we iterate over the `HashMap` and print the frequency of each element.
When you run this program, it will output:
Element 1 occurs 3 time(s)
Element 2 occurs 2 time(s)
Element 3 occurs 1 time(s)
Element 4 occurs 1 time(s)
Element 5 occurs 1 time(s)
This indicates that the number 1 occurs 3 times, the number 2 occurs 2 times, and the numbers 3, 4, and 5 occur once each in the given array.