簡體   English   中英

如何用Java編寫TreeMap的自定義比較器?

[英]How to write a custom Comparator for TreeMap in Java?

我想將鍵值對存儲在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

您可以將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()))

您可以按照以下步驟進行操作。

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

您需要為此編寫自己的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值,則可以添加處理。

您應該創建一個唯一的比較器來比較地圖的鍵。 但是因為您也想打印這些值,所以應該比較整個條目集:

Comparator<Map.Entry<String, String>> c = new Comparator<Map.Entry<String, String>>() {
  @Override
  public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
    int q = Integer.compare(o1.getKey().length(), o2.getKey().length());
    return q != 0 ? q : o1.getKey().compareTo(o2.getKey());
  }
};

然后可以使用此比較器進行排序:

map.entrySet().stream().sorted(c).forEach(System.out::println);

您可以使用此方法來代替將Map直接轉換為TreeMap

 public static Map toTreeMap(Map hashMap) 
    { 
        // Create a new TreeMap 
        Map treeMap = new TreeMap<>(new Comparator<Map.Entry<String, String>>(){

          public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2 ) 
       {
             if (o1.getKey().length() > o2.getKey().length()) {
                      return 1;
                }
            if (o1.getKey().length() > o2.getKey().length()) {
                      return -1;
               }
           return o1.getKey().compareTo(o2.getKey());
      }

      }); 

     for(Map.entry e : hashmap){
        treeMap.put(e.getKey(),e.getValue);
     }


        return treeMap; 

}

您可以在對TreeMap的構造函數調用中定義所需的Comparator<String>

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;


public class Main {
    static final Map<String, String> map = 
            new TreeMap<String, String> (new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            int diff_length = o1.length() - o2.length();
            if (diff_length != 0) return diff_length;
            return o1.compareTo(o2);
        }
    });

    public static final void main(String[] args) {
        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);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM