基于key对树图进行排序,其中key是可变的 [英] sorting treemap based on key, where key is variable

查看:137
本文介绍了基于key对树图进行排序,其中key是可变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于key是变量的键对树映射进行排序,因此排序应该基于变量值,我们如何实现这一点?我希望在构建的排序方法中使用rathar通过代码实现它,任何回复示例都有很大的帮助。

I want to sort the tree map based on the key where key is a variable,so sorting should be based on variable value, How can we achieve this? I want use in built sort method rathar implementing it through code, any reply with example is of great help.

推荐答案

TreeMap (实现 SortedMap )以正确的顺序自动存储密钥:

TreeMap (which implements SortedMap) stores automatically the keys in the correct order:

Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "three");
map.put(2, "two"); 
// prints one two three   
for(Integer key : map.keySet()) {
    System.out.println(map.get(key));
}

作为键类型(在这种情况下整数)你可以使用任何实现 可比较 (或者您可以提供 TreeMap 时,util / Comparator.htmlrel =noreferrer> Comparator

As Key-Type (in that case Integer) you can use any class which implements Comparable (or you can provide a Comparator when creating the TreeMap)

编辑:好的,这是一个如何重新映射地图的建议。

Okay, here is a suggestion how to re-map your map.

Map<Integer, String> oldMap; // get oldMap from somewhere
// Prepare remapping
Map<Integer, String> newMap = new TreeMap<Integer, String>();
Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
// Store a new key for each old key
keyMap.put(oldKey, newKey);
// fill the newMap
for(Integer oldKey : keyMap.keySet()) {
    newMap.put(keyMap.get(oldKey), oldMap.get(oldKey));
}
oldMap = newMap; // if needed

这篇关于基于key对树图进行排序,其中key是可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆