猿问

如何在 Java 中为 TreeMap 编写自定义比较器?

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


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


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


HUX布斯
浏览 177回答 3
3回答

紫衣仙女

您可以将 Comparator 作为参数传递给 Map 的构造函数。根据文档,它仅用于键:/**&nbsp;* Constructs a new, empty tree map, ordered according to the given&nbsp;* comparator.&nbsp; All keys inserted into the map must be <em>mutually&nbsp;* comparable</em> by the given comparator: {@code comparator.compare(k1,&nbsp;* k2)} must not throw a {@code ClassCastException} for any keys&nbsp;* {@code k1} and {@code k2} in the map.&nbsp; If the user attempts to put&nbsp;* a key into the map that violates this constraint, the {@code put(Object&nbsp;* key, Object value)} call will throw a&nbsp;* {@code ClassCastException}.&nbsp;*&nbsp;* @param comparator the comparator that will be used to order this map.&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; If {@code null}, the {@linkplain Comparable natural&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; ordering} of the keys will be used.&nbsp;*/public TreeMap(Comparator<? super K> comparator) {&nbsp; &nbsp; this.comparator = comparator;}通过这种方式,您可以通过密钥长度传递比较器,如下所示:new TreeMap<>(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))

万千封印

您需要为此编写自己comparator的并在 中使用它TreeMap,例如:public class StringComparator implements Comparator<String> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public int compare(String s1, String s2) {&nbsp; &nbsp; &nbsp; &nbsp; return s1.length() == s2.length() ? s1.compareTo(s2) : s1.length() - s2.length();&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, String> map = new TreeMap<>(new StringComparator());&nbsp; &nbsp; &nbsp; &nbsp; map.put("IBARAKI", "MitoCity");&nbsp; &nbsp; &nbsp; &nbsp; map.put("TOCHIGI", "UtunomiyaCity");&nbsp; &nbsp; &nbsp; &nbsp; map.put("GUNMA", "MaehashiCity");&nbsp; &nbsp; &nbsp; &nbsp; map.put("SAITAMA", "SaitamaCity");&nbsp; &nbsp; &nbsp; &nbsp; map.put("CHIBA", "ChibaCity");&nbsp; &nbsp; &nbsp; &nbsp; map.put("TOKYO", "Sinjyuku");&nbsp; &nbsp; &nbsp; &nbsp; map.put("KANAGAWA", "YokohamaCity");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(map);&nbsp; &nbsp; }}这不处理null值,但如果您null在用例中期望值,您可以添加处理。

不负相思意

您可以按如下方式执行此操作。&nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; Map<String, String> map = new TreeMap<>(new CustomSortComparator());&nbsp; &nbsp; &nbsp; map.put("IBARAKI", "MitoCity");&nbsp; &nbsp; &nbsp; map.put("TOCHIGI", "UtunomiyaCity");&nbsp; &nbsp; &nbsp; map.put("GUNMA", "MaehashiCity");&nbsp; &nbsp; &nbsp; map.put("SAITAMA", "SaitamaCity");&nbsp; &nbsp; &nbsp; map.put("CHIBA", "ChibaCity");&nbsp; &nbsp; &nbsp; map.put("TOKYO", "Sinjyuku");&nbsp; &nbsp; &nbsp; map.put("KANAGAWA", "YokohamaCity");&nbsp; &nbsp; &nbsp; System.out.println(map);&nbsp; }CustomSortComparator 的定义如下。public class CustomSortComparator implements Comparator<String> {&nbsp; @Override&nbsp; public int compare(String o1, String o2) {&nbsp; &nbsp; if (o1.length() > o2.length()) {&nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; }&nbsp; &nbsp; if (o1.length() < o2.length()) {&nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; return returnCompareBytes(o1, o2);&nbsp; }&nbsp; private int returnCompareBytes(String key1, String key2) {&nbsp; &nbsp; for (int i = 0; i < key1.length() - 1; i++) {&nbsp; &nbsp; &nbsp; if (key1.charAt(i) > key2.charAt(i)) {&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (key1.charAt(i) < key2.charAt(i)) {&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return 0;&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答