Skip to content

Instantly share code, notes, and snippets.

@mounicasrinivas
Last active December 26, 2023 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mounicasrinivas/29538bc88e105855f2ff64c18c83efcc to your computer and use it in GitHub Desktop.
Save mounicasrinivas/29538bc88e105855f2ff64c18c83efcc to your computer and use it in GitHub Desktop.
No Of Occurrences In An Array
public class NoOfOccuranceInAnArray {
public static void main(String[] args) {
//Given an integer array a and value v,
//find the number of Occurancences of v in a
int [] a = {1,2,2,2,2,3,4,5,5,6,7,7,};
int v = 2;
// Create a HashMap to store element-frequency pairs
Map<Integer,Integer> map = new HashMap<>();
// Iterate through the array to populate the HashMap
for(int i : a){
if(map.containsKey(i)){
// If the element is already in the map, increment its frequency
map.put(i,map.get(i) + 1);
}
else{
// If the element is not in the map, add it with a frequency of 1
map.put(i,1);
}
}
System.out.println(map.get(v));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment