簡體   English   中英

對HashMap及其嵌套的HashMap進行排序

[英]Sorting HashMap and its nested HashMap

我正在嘗試對嵌套的hashMaps進行排序,其中兩個HashMaps都需要進行排序。

第一個hashMap應該按鍵排序。 第二個應該按值排序。 到目前為止,我設法通過對鍵進行數組排列並對第一個hashMap的鍵進行排序。

我的哈希圖看起來像這樣

 HashMap<String,HashMap<String,Integer>> carOwners = new 
                                    HashMap<String,HashMap<String, Integer>>();

舉例來說,假設我們的第一個String是Name,car brand,qnty。

例如:David:

奧迪> 5

寶馬> 4

伊莎貝爾:

大眾> 10

MB> 4

因此,基本上,我們首先對名稱進行排序,然后對嵌套哈希值按值進行排序。 如何做到這一點...找不到任何有用的信息:(>

要對Map排序,可以使用以下類: TreeMap 官方文件所述

根據映射鍵的自然順序或在映射創建時提供的Comparator對映射進行排序,具體取決於所使用的構造函數。

如果要按插入順序對元素進行排序 ,請使用LinkedHashMap

此鏈表定義了迭代順序,通常是將鍵插入映射的順序(插入順序)。

有關按值對Map進行排序的信息,請參見這篇文章 它也適用於Java7和Java8。

希望能幫助到你。

將第一個地圖設為TreeMap,將第二個地圖設為按值排序。 推薦這個職位

以下是您的問題的代碼段。

public static void main(String[] args) {
    Map<String, HashMap<String, Integer>> carOwners = new TreeMap<String, HashMap<String, Integer>>();
    HashMap<String, Integer> nameQuantity = new HashMap<String, Integer>();
    nameQuantity.put("Audi", 5);
    nameQuantity.put("BMW", 4);
    carOwners.put("David", sortByValue(nameQuantity)); 
    nameQuantity = new HashMap<String, Integer>();
    nameQuantity.put("VW", 10);
    nameQuantity.put("MB", 4);
    carOwners.put("Izabel", sortByValue(nameQuantity)); 
    for (Map.Entry<String, HashMap<String, Integer>> carOwnerEntry : carOwners.entrySet()) {
        System.out.println(carOwnerEntry.getKey());
        HashMap<String, Integer> nameQty = carOwnerEntry.getValue();
        for (Map.Entry<String, Integer> nameQtyEntry : nameQty.entrySet()) {
            System.out.println(nameQtyEntry.getKey() + " " + nameQtyEntry.getValue());
        }
    }

public static <K, V extends Comparable<? super V>> HashMap<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        });
    HashMap<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

暫無
暫無

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

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