I have an int array:
{1,2,4,2,3,5,6,4,3}
How can I find frequencies of array elements like 1=1,2=2,3=2,4=4..
. I need a class w
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);
}
}
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);
}
I have a solution for count the frequency of elements in a java array
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ItemCount {
public static void main(String[] args)
{
try{
int count=1,index=1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Size of array : ");
int size=Integer.parseInt(br.readLine());
System.out.print("Enter the Elements of array : ");
int arr[]=new int[size];
for(int i=0;i<arr.length;i++)
{
System.out.print("arr["+i+"] : ");
arr[i]=Integer.parseInt(br.readLine());
}
System.out.print("Sorted Array is :");
SortingArray.sortDescendind(arr);
for(int i=0;i<arr.length;i++)
{
System.out.println("arr["+i+"] : "+arr[i]);
}
for(int i=0;i<arr.length;)
{
count=1;
for(index=i+1;index<arr.length;index++)
{
if(arr[i]==arr[index])
{
count++;
}
else{
break;
}
}
System.out.println(""+arr[i] +"----> "+count);
i+=count;
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
/// you can select any sorting method for array---->SortingArray.sortDescendind(arr)