我想按对象的值对 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模板网!