-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountEachElement.java
More file actions
31 lines (22 loc) · 923 Bytes
/
Copy pathCountEachElement.java
File metadata and controls
31 lines (22 loc) · 923 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
public class CountEachElement{
public static Map<Integer, Integer> countElements(int[] arr) {
Map<Integer, Integer> countMap = new HashMap<>();
for(int element : arr) {
countMap.put(element, countMap.getOrDefault(element, 0) + 1);
}
return countMap;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = {1,1,3,4,2,2,2};
Map<Integer,Integer> result = countElements(array);
for(Map.Entry<Integer, Integer> entry : result.entrySet()) {
System.out.println("Element " + entry.getKey() +
" occurs " + entry.getValue() + " times");
}
}
// allow me to count all the elements occured in an array