// Java code to implement the approach
import java.io.*;
import java.util.*;
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value)
{
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
class GFG {
// Function to find the most frequent element
static List<Pair<Integer, Character> >
findMostFrequent(char[][] arr, int n)
{
// Map to store the frequency
// of each character
Map<Character, Integer> unmap = new HashMap<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
unmap.put(arr[i][j],
unmap.getOrDefault(arr[i][j], 0)
+ 1);
}
}
// To store the frequency of character
List<Pair<Integer, Character> > arr2
= new ArrayList<>();
for (Map.Entry<Character, Integer> entry :
unmap.entrySet()) {
arr2.add(new Pair<>(entry.getValue(),
entry.getKey()));
}
// Sort the array
Collections.sort(
arr2,
new Comparator<Pair<Integer, Character> >() {
@Override
public int compare(
Pair<Integer, Character> o1,
Pair<Integer, Character> o2)
{
return o2.getKey().compareTo(
o1.getKey());
}
});
return arr2;
}
public static void main(String[] args)
{
// Size of the matrix
int N = 3;
// Initialize the 2D array
char[][] arr = { { 'a', 'a', 'a' },
{ 'b', 'a', 'c' },
{ 'd', 'c', 'a' } };
// Function call
List<Pair<Integer, Character> > ans
= findMostFrequent(arr, N);
// Print the answer
for (int i = 0; i < ans.size(); i++) {
System.out.println(ans.get(i).getValue() + " : "
+ ans.get(i).getKey());
}
}
}
// This code is contributed by lokesh.