Here's a Java program to count the occurrences of each element in an array:
import java.util.HashMap;
import java.util.Map;
public class ElementOccurrencesCounter {
public static Map<Integer, Integer> countOccurrences(int[] arr) {
Map<Integer, Integer> occurrencesMap = new HashMap<>();
// Iterate through the array and count occurrences of each element
for (int num : arr) {
if (occurrencesMap.containsKey(num)) {
// If the element is already in the map, increment its count
occurrencesMap.put(num, occurrencesMap.get(num) + 1);
} else {
// If the element is not in the map, add it with count 1
occurrencesMap.put(num, 1);
}
}
return occurrencesMap;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1};
// Count occurrences of each element in the array
Map<Integer, Integer> occurrences = countOccurrences(arr);
// Print the occurrences of each element
System.out.println("Element occurrences:");
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
System.out.println("Element " + entry.getKey() + ": " + entry.getValue() + " occurrences");
}
}
}
```
In this program:
- The `countOccurrences` method takes an array of integers as input and returns a `Map<Integer, Integer>` where the keys represent distinct elements of the array and the values represent the number of occurrences of each element.
- Within the method, we use a `HashMap` to store the occurrences of each element.
- We iterate through the array, and for each element:
- If the element is already present in the `HashMap`, we increment its count.
- If the element is not present, we add it to the `HashMap` with a count of 1.
- In the `main` method, an example array is initialized.
- We call the `countOccurrences` method to count the occurrences of each element in the array.
- Finally, we print the occurrences of each element.