按值排序HashMap [英] Sorting HashMap by values
本文介绍了按值排序HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据存储在其中的值对我的 HashMap
进行排序。 HashMap
包含存储在手机中的联系人姓名。
I need to sort my HashMap
according to the values stored in it. The HashMap
contains the contacts name stored in phone.
另外,我需要尽快将键自动排序我对这些值进行排序,或者您可以将键和值绑定在一起,因此值中的任何更改都应该反映在键中。
Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound together thus any changes in values should get reflected in keys.
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"froyo");
map.put(2,"abby");
map.put(3,"denver");
map.put(4,"frost");
map.put(5,"daisy");
必需输出:
Required output:
2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;
推荐答案
假设Java,可以像这样对hashmap进行排序:
Assuming Java, you could sort hashmap just like this:
public LinkedHashMap<Integer, String> sortHashMapByValues(
HashMap<Integer, String> passedMap) {
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer, String> sortedMap =
new LinkedHashMap<>();
Iterator<String> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
String val = valueIt.next();
Iterator<Integer> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Integer key = keyIt.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
只是一个开球的例子。这种方式更有用,因为它对HashMap进行排序并保留重复值。
Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.
这篇关于按值排序HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文