如何用Java编写TreeMap的自定义比较器?

问题描述:

我想将键值对存储在TreeMap中,并根据以下逻辑基于Key的值对条目进行排序:

I want to store key-value pairs in TreeMap and sort the entries based on the value of Key as per following logic:

按键的长度排序。如果两个键的长度相同,则按字母顺序对其进行排序。例如,对于以下键值对。

Sort by the length of the key. If the length of two keys is same then sort them alphabetically. Example, for the following key-value pairs.

IBARAKI MitoCity
TOCHIGI UtunomiyaCity
GUNMA MaehashiCity
SAITAMA SaitamaCity
CHIBA ChibaCity
TOKYO Sinjyuku
KANAGAWA YokohamaCity

预期的输出是这样的。

CHIBA : ChibaCity
GUNMA : MaehashiCity
TOKYO : Sinjyuku
IBARAKI : MitoCity
SAITAMA : SaitamaCity
TOCHIGI : UtunomiyaCity
KANAGAWA : YokohamaCity


为此您需要编写自己的比较器并将其用于 TreeMap ,例如:

You need to write your own comparator for this and use it in TreeMap, e.g.:

public class StringComparator implements Comparator<String> {

    @Override
    public int compare(String s1, String s2) {
        return s1.length() == s2.length() ? s1.compareTo(s2) : s1.length() - s2.length();
    }

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        Map<String, String> map = new TreeMap<>(new StringComparator());
        map.put("IBARAKI", "MitoCity");
        map.put("TOCHIGI", "UtunomiyaCity");
        map.put("GUNMA", "MaehashiCity");
        map.put("SAITAMA", "SaitamaCity");
        map.put("CHIBA", "ChibaCity");
        map.put("TOKYO", "Sinjyuku");
        map.put("KANAGAWA", "YokohamaCity");

        System.out.println(map);
    }

}

此操作不处理 null 值,但如果在用例中期望 null 值,则可以添加处理。

This does not handle null values but you can add the handling if you are expecting null values in your use case.