find the frequency of elements in a java array
Solution 1:
class MapTest
{
public static void main(String args[]){
HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
int arr[] = new int[]{2,2,3,3,5,6,7,9,9,0};
for(int i=0; i<arr.length; i++){
if(h.containsKey(arr[i])){
h.put(arr[i], h.get(arr[i]) + 1);
} else {
h.put(arr[i], 1);
}
}
System.out.println(h);
}
}
Solution 2:
In Java 8 you can do this
Map<Integer, Long> freq = Arrays.stream(array).boxed().
collect(Collectors.groupingBy(Integer::intValue, Collectors.counting()));
Solution 3:
You have to do a few things:
- Define an upper and lower bound for your range of numbers.
- Establish a convenient object/data structure to store occurrences of these numbers.
- Iterate through the passed-in array and count all occurrences of each number, storing the result in the convenient object/data structure.
If this is done in a simple manner, it could be only a matter of reading the elements from the passed-in array and printing out the final result.
Solution 4:
If range of the elements of the array is specified and limited to array size, the best solution is using hash map. T(n) = O(n), auxiliary space = O(n).
public static void findCount3(int[] a){
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
for(int i = 0; i < a.length; i++){
if(!hm.containsKey(a[i])){
hm.put(a[i], 1);
}else{
hm.put(a[i], hm.get(a[i])+1);
}
System.out.println(hm);
}
Solution 5:
import java.util.*;
class Findfreqarray
{
public static void main(String args[])
{
int t, i, j, len, count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements to insert in an array: ");
len = in.nextInt();
int[] arr = new int[len];
System.out.println("Enter elements to insert in an array: ");
for(i=0;i<len;i++)
{
t = in.nextInt();
arr[i] = t;
}
System.out.println("\n");
for(i=0;i<len;i++)
{
count=1;
for(j=i+1;j<=len-1;j++)
{
if(arr[i]==arr[j] && arr[i]!='\0')
{
count++;
arr[j] = '\0';
}
}
if(arr[i]!='\0')
{
System.out.println(arr[i] + " is " + count + " times.\n");
}
}
}
}