forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Closes Issue jainaman224#1601 (jainaman224#1744)
Added Count Frequency Of Elements In Java For issue jainaman224#1601
- Loading branch information
1 parent
facf945
commit f2e071c
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
62 changes: 62 additions & 0 deletions
62
Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
/*Problem Statement | ||
* Given an array of elements count the frequency of every element in the array. | ||
*/ | ||
|
||
import java.util.HashMap; | ||
import java.util.Scanner; | ||
|
||
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(); | ||
} | ||
|
||
// function to count frequency | ||
private static void countFreq(int[] a, int n) { | ||
// using hashmap to store the freq | ||
HashMap<Integer, Integer> hm = new HashMap<>(); | ||
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 | ||
* */ |