Skip to content

Commit

Permalink
Count Frequency Of Elemets In Java Fixex jainaman224#1601
Browse files Browse the repository at this point in the history
  • Loading branch information
chanpreet1999 authored Feb 29, 2020
1 parent b595add commit 6e242f4
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.HashMap;
import java.util.Scanner;


/*Problem Statement
* Given an array of elements count the frequency of every element in the array.
*/

public class CountFrequencyOfArrayElements {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

//input size of array
int n = sc.nextInt();

//input array
int a[] = new int[n];
for(int i = 0; i < n; i++)
a[i] = sc.nextInt();

countFreq(a, n);
sc.close();
}

private static void countFreq(int[] a, int n) {
HashMap<Integer, Integer> hm = new HashMap<>(); // using hashmap to store the freq

for(int i = 0; i < n; i++)
{
if( hm.containsKey(a[i]) )
hm.put( a[i], hm.get(a[i]) + 1);
else
hm.put(a[i], 1);
}

//display the frequencies
System.out.println("Element \t Frequency");
hm.forEach(
(k,v) ->
{
System.out.println(k+" \t\t "+v);
}
);
}

}

/*
* Input :
5
2 1 1 6 1
* Output :
Element Frequency
1 3
2 1
6 1
* */

0 comments on commit 6e242f4

Please sign in to comment.