gpt4 book ai didi

java - 遍历Hash Map key的值是按降序还是升序?

转载 作者:行者123 更新时间:2023-11-30 07:46:47 25 4
gpt4 key购买 nike

我试图以降序或升序遍历 HashMap ,但没有得到正确的输出。

这是我的 map :

Hashmap<String Integer> hm= new Hashmap<String,Integer>();

这是我的值(value)观:

Key    Value
Hi 4
kumar 1
Hello 1
vivek 3

我正在尝试这样的事情:

List<Integer> ValueList = new ArrayList<Integer>(hm.values());
ArrayList<String> keyList = new ArrayList<String>(hm.keySet());

Collections.sort(ValueList);
Collections.reverse(keyList);
Collections.reverse(ValueList);

我想要这样的东西:

Key    Value
kumar 1
Hello 1
vivek 3
Hi 4

最佳答案

我建议使用Apache Commons Collections ListOrderedMap。解决办法如下:

//Populate the map
Map<String, Integer> map = new HashMap<>();
map.put("Hi", 4);
map.put("kumar", 1);
map.put("Hello", 1);
map.put("vivek", 3);

//Sort the values
List<Integer> values = new ArrayList<Integer>(map.values());
Collections.sort(values);

int size = values.size();
Set<Entry<String, Integer>> entries = map.entrySet();

//Create a new ordered map
ListOrderedMap<String, Integer> orderedMap;
orderedMap = ListOrderedMap.listOrderedMap(new HashMap<String, Integer>(map));

for (int i = 0; i < size; i++) {

Integer value = values.get(i);
Iterator<Entry<String, Integer>> iter = entries.iterator();

while (iter.hasNext()) {
Entry<String, Integer> entry = iter.next();
if (value.equals(entry.getValue())) {
//Put all values at index i that match the value
orderedMap.put(i, entry.getKey(), value);
}
}
}

//Print the orderedMap key/value pairs
entries = orderedMap.entrySet();
for (Entry<String, Integer> entry : entries) {
final String key = entry.getKey();
final Integer value = entry.getValue();
System.out.println("key = " + key + ", value = " + value);
}

输出:

key = Hello, value = 1
key = kumar, value = 1
key = vivek, value = 3
key = Hi, value = 4

关于java - 遍历Hash Map key的值是按降序还是升序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33812270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com