Java Online Compiler
Example: SortArrayByFrequencyHashMap in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SortArrayByFrequencyHashMap import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] arr = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}; System.out.println("Original Array: " + Arrays.toString(arr)); // Step 1: Count the frequency of each element Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : arr) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } // Step 2: Create a list of elements from the original array // This list will be sorted based on frequencies List<Integer> list = new ArrayList<>(); for (int num : arr) { list.add(num); } // Step 3: Sort the list using a custom comparator Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer n1, Integer n2) { // Get frequencies from the map int freq1 = frequencyMap.get(n1); int freq2 = frequencyMap.get(n2); // Compare frequencies in decreasing order if (freq1 != freq2) { return freq2 - freq1; // For decreasing frequency } else { // If frequencies are same, compare numbers in ascending order return n1 - n2; } } }); System.out.println("Sorted by Frequency (Decreasing): " + list); } }
Output
Clear
ADVERTISEMENTS