本文介紹了對 Hashmap<String, Object> 中的 Object 的值進行排序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想按對象的值對 Hashmap 進行排序.在這種情況下,按國家/地區代碼.
I want to sort an Hashmap by the object's value. In this case, by country code.
KEY OBJECT
String LoyaltyCountry
- country name
- country code
- country loc
我的代碼如下:
public static HashMap<String, LoyaltyCountry> loyaltyCountrySortMap(HashMap<String, LoyaltyCountry> loyaltyCountryMap) {
if (loyaltyCountryMap != null) {
List keys = new ArrayList();
keys.addAll(loyaltyCountryMap.keySet());
Collections.sort(keys, new Comparator<LoyaltyCountry>() {
public int compare(LoyaltyCountry o1, LoyaltyCountry o2) {
return o1.getCountryName().compareTo(o2.getCountryName());
}
});
}
return loyaltyCountryMap;
}
我怎樣才能正確地做到這一點?
How can I do this correctly?
推薦答案
這是一個返回 Set 的方法,該 Set 包含按其值排序的 Map.Entry 項.
Here is a method that returns a Set containing the Map.Entry items sorted by their value.
public static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(Map<K, V> map) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
這篇關于對 Hashmap<String, Object> 中的 Object 的值進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!