How to Find Frequency of Elements in int Array Using HashMap

Jaskirat Singh
Jan 30, 2021

--

We will understand how to find frequency of integer array elements in java. There are different ways for finding frequency of array elements, however in this post we will understand how to find frequency using HashMaps, which is probably the simplest and easiest way.

Java HashMap class implements the Map interface. It allows us to store key and value pair, and keys should be unique. Java HashMap is non synchronized and maintains no order.

Main Points:-

Declaration of HashMap:-
HashMap<Integer, Integer> hm = new HashMap<>();
If element already exists, just increase the count:-
hm.put(arr[i],hm.get(arr[i])+1);
If unique element found:-
hm.put(arr[i],1);
Entire working code in java

Output: {64=1, 96=1, 65=1, 52=1, 5=2, 53=1, 22=1, 54=1, 7=1, 42=1, 12=3}

Photo by Arnold Francisca on Unsplash

--

--

Jaskirat Singh
Jaskirat Singh

Written by Jaskirat Singh

A young and enthusiastic developer, computer science undergraduate and cosmos lover

No responses yet