简体   繁体   English

自定义比较器,用于根据每个字符的频率对字符串进行排序

[英]Custom Comparator for sorting string based on frequency of each character

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?假设数组是一个字符数组,hashmap 是每次比较两个字符时填充,还是填充一次然后根据填充映射的频率决定顺序?

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.您正在实例化比较器并将其作为参数传递给Arrays.sort方法,这意味着只有一个实例,因此HashMap被填充一次。

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.比较器被实例化一次,由于 map 被填充到构造函数中,因此将被填充一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM