Write a java program to sort elements in descending order according to their frequency. If the two elements have same frequency then output them in the order of their input.

Example:

Store the input into List and HaspMap. Sort the list according to the count stored in the HashMap. For this, we need to implement the comparator Interface.

Override the compare method, return 0 if the frequency (i.e count) of the two number is same otherwise return the frequency difference.

Recommended: Comparator Interface in Java

import java.util.*;

public class SortByFrequency {

    public static void main(String args[]){

        Scanner in = new Scanner(System.in);
        int n, num;

        System.out.println("Enter n");
        n = in.nextInt();

        HashMap map = new HashMap<>(n);

        List output = new ArrayList<>(n);

        System.out.println("Enter "+n+" Elements");
        for(int i=0; i{

    HashMap map;

    Frequency(HashMap map){
        this.map = map;
    }

    @Override
    public int compare(Integer o1, Integer o2) {
        int f1 = map.get(o1), f2 = map.get(o2);
        if(f1 == f2)
            return 0;
        else
            return (f2 -f1);
    }
}

Output

Leave a Reply

2 × five =