簡體   English   中英

如何對具有鍵值對的列表列表進行排序?

[英]How to sort a map of list having key-value pairs?

我在地圖中獲取特定鍵的結果列表。 如何排序?

提前致謝。

如果您想對鍵進行排序,請選擇TreeMap


從您的陳述:

我在地圖中獲取特定鍵的結果列表。 如何排序?

看來你的地圖是

Map<String,List<SomeEntity>> map;

您可以從key獲取對象List ,然后使用

Collections.sort(list, your_custom_implementation_of_comparator)

public class CustomComparator implements Comparator<SomeEntity> {
    @Override
    public int compare(SomeEntity o1, SomeEntity o2) {
        //logic goes here
    }
}

如果您詢問如何對列表進行排序,請參見Collections.sort(List)

Map<String, String> mapie = new Hashtable<String, String>();
        mapie.put("D", "the letter D");
        mapie.put("C", "the letter C");
        mapie.put("A", "the letter A");
        mapie.put("B", "the letter B");

        Set<String> keys = mapie.keySet();

        List<String> keyColList = new ArrayList<String>();
        keyColList.addAll(keys);

            **You can also make use of a Comparator if you are using a custom object.**
        Collections.sort(keyColList);

        for(String keyIndex:keyColList){
            System.out.println("Key: "+ keyIndex + " has value: "+mapie.get(keyIndex));
        }

進行視覺檢查的最簡單方法是使用地圖初始化TreeMap,然后打印它。

System.out.println("map: " + new TreeMap(myMap));

暫無
暫無

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

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