为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUX布斯 2022-06-04 11:02:19
我想将键值对存储在 TreeMap 中,并根据以下逻辑根据 Key 的值对条目进行排序:按密钥长度排序。如果两个键的长度相同,则按字母顺序对其进行排序。例如,对于以下键值对。IBARAKI MitoCityTOCHIGI UtunomiyaCityGUNMA MaehashiCitySAITAMA SaitamaCityCHIBA ChibaCityTOKYO SinjyukuKANAGAWA YokohamaCity预期的输出是这样的。CHIBA : ChibaCityGUNMA : MaehashiCityTOKYO : SinjyukuIBARAKI : MitoCitySAITAMA : SaitamaCityTOCHIGI : UtunomiyaCityKANAGAWA : YokohamaCity
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

您可以将 Comparator 作为参数传递给 Map 的构造函数。根据文档,它仅用于键:


/**

 * Constructs a new, empty tree map, ordered according to the given

 * comparator.  All keys inserted into the map must be <em>mutually

 * comparable</em> by the given comparator: {@code comparator.compare(k1,

 * k2)} must not throw a {@code ClassCastException} for any keys

 * {@code k1} and {@code k2} in the map.  If the user attempts to put

 * a key into the map that violates this constraint, the {@code put(Object

 * key, Object value)} call will throw a

 * {@code ClassCastException}.

 *

 * @param comparator the comparator that will be used to order this map.

 *        If {@code null}, the {@linkplain Comparable natural

 *        ordering} of the keys will be used.

 */

public TreeMap(Comparator<? super K> comparator) {

    this.comparator = comparator;

}

通过这种方式,您可以通过密钥长度传递比较器,如下所示:


new TreeMap<>(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))



查看完整回答
反对 回复 2022-06-04
?
万千封印

TA贡献1891条经验 获得超3个赞

您需要为此编写自己comparator的并在 中使用它TreeMap,例如:


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在用例中期望值,您可以添加处理。


查看完整回答
反对 回复 2022-06-04
?
不负相思意

TA贡献1777条经验 获得超10个赞

您可以按如下方式执行此操作。


  public static void main(String[] args) {


      Map<String, String> map = new TreeMap<>(new CustomSortComparator());


      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);


  }

CustomSortComparator 的定义如下。


public class CustomSortComparator implements Comparator<String> {


  @Override

  public int compare(String o1, String o2) {

    if (o1.length() > o2.length()) {

      return 1;

    }

    if (o1.length() < o2.length()) {

      return -1;

    }

    return returnCompareBytes(o1, o2);

  }


  private int returnCompareBytes(String key1, String key2) {

    for (int i = 0; i < key1.length() - 1; i++) {

      if (key1.charAt(i) > key2.charAt(i)) {

        return 1;

      }

      if (key1.charAt(i) < key2.charAt(i)) {

        return -1;

      }

    }

    return 0;

  }

}


查看完整回答
反对 回复 2022-06-04
  • 3 回答
  • 0 关注
  • 176 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号