Find k numbers with most occurrences in an array in Java

In this module, we are going to discuss finding the most occurrences of elements in an array in Java. Here, we print the elements with the most frequency. we print all those elements until K elements which have the highest frequencies. The main objective is to identify elements with the most number of occurrences.

Test Criteria

```Input arr={32,55,9,22,22,32,35,9} k=2
The output is 2 elements which are 22 and 32 with most occurrences k=2,elements={32,22}
Input arr={32,35,36,9,32}  k=3
The output is 1 element which is 32 with most occurrences k=1,elements={32,35,36}```

Implementation of Code to Find Numbers with Most Occurrences

```import java.io.*;
import java.util.*;
public class occurences {
public static Map<Integer,Integer> freq(int arr[],int n)
{
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n;i++)                     //create HashMap if key presnt in hash map increase it's value
{
if(map.containsKey(arr[i]))
{
map.put(arr[i],map.get(arr[i])+1);
}
else
{
map.put(arr[i],1);             //if not present assign it to hash map with value 1
}
}
return map;
}
public static void main(String args[])throws IOException {
int n=s.length;
int arr[]=new int[n];
for(int i=0;i<n;i++)
{  arr[i]=Integer.parseInt(s[i]);}
Map<Integer,Integer> map=new HashMap<>();
map=freq(arr,n);
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));    //Sort in decreasing order of values
Set entrySet = reverseSortedMap.entrySet();
Iterator it = entrySet.iterator();
while(k-->0)
{
System.out.print(it.next()+"  ");
}
}
}```

Input 1:

```32 55 9 22 22 32 35 9
2```

Output 1:

`32=2  22=2`

Input 2:

```32 35 36 9 32
3```

Output 2:

`32=2  35=1  36=1`

Explanation:

Here we used HashMap to identify the frequencies of elements and then we use the LinkedHashMap to iterate the frequencies of elements in decreasing order which is stored in reverseSortedMap. Later, we used the k number of elements with the highest frequencies to print elements using iterator.

```LinkedHashMap<Integer, Integer> reverseSortedMap = new LinkedHashMap<>();
map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));```

The above code gives a description of sorting the HashMap values in descending order based on values.