From f2e071c5861254b566c7763619552cd40a435ca5 Mon Sep 17 00:00:00 2001 From: Chanpreet Singh <34856246+chanpreet1999@users.noreply.github.com> Date: Wed, 18 Mar 2020 18:18:11 +0530 Subject: [PATCH] Closes Issue #1601 (#1744) Added Count Frequency Of Elements In Java For issue #1601 --- .../CountFrequencyOfArrayElements.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java diff --git a/Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java b/Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java new file mode 100644 index 0000000000..d443032789 --- /dev/null +++ b/Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java @@ -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 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 + + * */