Home > Back-end >  Custom Comparator for sorting string based on frequency of each character
Custom Comparator for sorting string based on frequency of each character

Time:11-25

I made a custom comparator for sorting a string based on the frequency of characters in it.

public class CustomComparator implements Comparator<Character> {
    HashMap<Character,Integer> map;
    public CustomComparator(String s) {
        this.map = new HashMap<>();
        for(char ch : s.toCharArray()) {
            map.put(ch,map.getOrDefault(ch,0) 1);
        }
    }
    @Override
    public int compare(Character ch1,Character ch2) {
        return map.get(ch2) - map.get(ch1);
    }
}

Arrays.sort(array,new CustomComparator(s));

Assume array is an Character array, is the hashmap filled everytime a comparison between two chars are made, or it is filled once and then order is decided based on filled map's frequencies?

CodePudding user response:

You are instantiating the comparator and passing it as a parameter to the Arrays.sort method, that means that there will only be one instance and therefore the HashMap is filled once.

It's the same as if it were written like this:

public class CustomComparator implements Comparator<Character> {
    //... same as yours
}

CustomComparator cs = new CustomComparator(s);
Arrays.sort(array, cs);

The comparator is instantiated once and since the map is filled in the constructor, it will be filled once.

  • Related