Sort the Object#39;s value inside the Hashmaplt;String, Objectgt;(对 HashmapString, 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 的值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对 Hashmap<String, Object> 中的 Object 的值进行排


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01