簡體   English   中英

如何使用鍵降序對哈希映射進行排序

[英]How to sort a hash map using key descending order

如何使用鍵降序對哈希映射進行排序。 請舉例說明。 以及對哈希映射進行排序的方法有多少。 請詳細說明

HashMap不支持排序。 它們只是根據鍵的hashCode值將條目存儲在存儲桶中,它們如何看待它是否合適。 它們適用於存儲事物並在事后查找它們,但不適合迭代它們的內容(這是你顯然想做的事情)因為你不能依賴它們的順序並且迭代它通常很昂貴。

請嘗試使用TreeMap 您可以指定一個自定義比較器,它只執行默認比較器的反轉。 在這種情況下,您的參賽作品將按降序排序。 Collections.reverseOrder將為您創建這樣的比較器,您可以像這樣使用它:

new TreeMap<Integer, String>(Collections.reverseOrder());

完成此任務的兩種方法:

  1. 使用HashMap

     public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 34); map.put("B", 25); map.put("C", 50); map.put("D", 50); // "duplicate" value System.out.println(entriesSortedByValues(map)); } static <K, V extends Comparable<? super V>> List<Entry<String, Integer>> entriesSortedByValues(Map<String, Integer> map) { List<Entry<String, Integer>> sortedEntries = new ArrayList<Entry<String, Integer>>(map.entrySet()); Collections.sort(sortedEntries, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) { return e2.getKey().compareTo(e1.getKey()); } }); return sortedEntries; } 
  2. 使用Tree Map ,編寫自己的Comparator

     public class Test2 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("A", 34); map.put("B", 25); map.put("C", 50); map.put("D", 50); MyComparator comp = new MyComparator(map); Map<String, Integer> newMap = new TreeMap(comp); newMap.putAll(map); System.out.println(newMap); } } class MyComparator implements Comparator { Map map; public MyComparator(Map map) { this.map = map; } @Override public int compare(Object o1, Object o2) { return (o2.toString()).compareTo(o1.toString()); } } 

我建議使用Java 8中包含的此方法。

List<Map.Entry<String, Integer>> sorted_map =
                map_1.entrySet()
                .stream()
                .sorted(reverseOrder(Map.Entry.comparingByKey()))
                .collect(Collectors.toList());

這里'map_1'是您要排序的地圖。

現在,您可以使用sorted_map變量進行迭代並用於您的目的。

確保 :

import static java.util.Collections.reverseOrder;

試試這個代碼

public class MapUsingSort {
public static void main(String[] args) {

Map<Integer, String> abc = new HashMap<>();
abc.put(3, "a");
abc.put(6, "b"); 
abc.put(1, "c");
abc.put(4, "h");
abc.put(10, "k");
abc.put(9, "x");

 // Map is stored in ArrayList
List<Entry<Integer,String>> sortedEntries = new 
ArrayList<Entry<Integer,String>>(abc.entrySet());


Collections.sort(sortedEntries, new Comparator<Entry<Integer,String>>() {
 @Override
 public int compare(Entry<Integer, String> a, Entry<Integer, String> b) 
 {
    //Sorting is done here make changes as per your need 
    // swap a and b for descending order in return statement 

    return a.getKey().compareTo(b.getKey());   
 }
});

 for (Object object : sortedEntries) {

  //print your data in your own way
  System.out.println((Map.Entry)object);
  }
 }
}
  HashMap<Integer, String> hmap = new HashMap<Integer, String>();
         hmap.put(5, "A");
         hmap.put(11, "C");
         hmap.put(4, "Z");
         hmap.put(77, "Y");
         hmap.put(9, "P");
         hmap.put(66, "Q");
         hmap.put(0, "R");

         System.out.println("Before Sorting:");
         Set set = hmap.entrySet();
         Iterator iterator = set.iterator();
         while(iterator.hasNext()) {
               Map.Entry me = (Map.Entry)iterator.next();
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
         }
         Map<Integer, String> map = new TreeMap<Integer, String>(hmap); 
         System.out.println("After Sorting:");
         Set set2 = map.entrySet();
         Iterator iterator2 = set2.iterator();
         while(iterator2.hasNext()) {
              Map.Entry me2 = (Map.Entry)iterator2.next();
              System.out.print(me2.getKey() + ": ");
              System.out.println(me2.getValue());
         }
    }

暫無
暫無

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

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