簡體   English   中英

按鍵按升序排序地圖

[英]Sort Map in Ascending Order by Key

我正在嘗試根據鍵按升序對Map進行排序。 鑒於Map

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

map.put(5, "five");
map.put(1, "one");
map.put(3, "three");
map.put(0, "zero");

我想訂購:

0, zero
1, one
3, three
5, five

我編寫了以下代碼來完成此任務:

    public <K, V extends Comparable<? super V>> Map<K, V> sortByKeyInAscendingOrder(Map<K, V> map)
{
    List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
    list.sort(Entry.comparingByKey());

    Map<K, V> result = new LinkedHashMap<>();
    for (Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

但是,當我調用sort()我收到以下錯誤:

The method sort(Comparator<? super Map.Entry<K,V>>) in the type List<Map.Entry<K,V>> is not applicable for the arguments (Comparator<Map.Entry<Comparable<? super Comparable<? super K>>,Object>>)

我寫了類似的代碼(工作正常)按值排序(將Entry.comparingByKey()更改為Entry.comparingByValue() )但由於某種原因,當我嘗試按鍵排序時,我得到上述錯誤。

我怎樣才能解決這個問題?

謝謝

方法comparingByKey需要其關鍵, K類型參數,是Comparable ,不(一定)它的值, V

移動綁定? extends Comparable<? super K> ? extends Comparable<? super K> ? extends Comparable<? super K>VK 更改

<K, V extends Comparable<? super K>>

<K extends Comparable<? super K>, V>

當然, V也可以是可Comparable ,但是使該綁定引用自身,而不是K

V extends Comparable<? super V>

你需要把K比作它的排序; 並且V上的界限是錯誤的(但無論如何都是不必要的)。

public <K extends Comparable<? super K>, V> Map<K, V> sortByKeyInAscendingOrder(Map<K, V> map)

請注意,一種更簡單的方法可能是:

return new LinkedHashMap<>(new TreeMap<>(map));

要么

return map.entrySet().stream()
    .sorted(Entry.comparingKey())
    .collect(toMap(k -> k, v -> v, LinkedHashMap::new));

使用TreeMap怎么樣? 它保持鍵按自然順序排序:

https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

如果需要從現有地圖創建它,請使用它的參數化構造函數:

TreeMap<Integer,String> treeMap = new TreeMap<>(map);

因為使用HashMap不保證順序,LinkedHashMap維護插入順序。 要保持按鍵排序的地圖,請使用TreeMap。

您也可以嘗試使用java 8流

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

    map.put(5, "five");
    map.put(1, "one");
    map.put(3, "three");
    map.put(0, "zero");

    map = map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    System.out.println(map);  //{0=zero, 1=one, 3=three, 5=five}

或者你可以在Map上使用forEach

map.forEach((k,v)->System.out.println(k+"  "+v));

暫無
暫無

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

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