亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 202 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號