基于key对树图进行排序,其中key是可变的
我想根据键是一个变量的键对树映射进行排序,因此排序应该基于变量值,我们如何实现这一点? 我希望在构建的排序方法中使用rathar通过代码实现它,任何回复示例都有很大的帮助。
TreeMap
(实现SortedMap
)以正确的顺序自动存储密钥:
Map map = new TreeMap(); 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)); }
作为Key-Type(在这种情况下为Integer
),您可以使用任何实现Comparable
类(或者您可以在创建TreeMap
时提供Comparator
)
编辑:好的,这是一个如何重新映射你的地图的建议。
Map oldMap; // get oldMap from somewhere // Prepare remapping Map newMap = new TreeMap(); Map keyMap = new HashMap(); // 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
TreeMap
实现了SortedMap
接口,并按其键排序,无需执行任何操作:
地图根据其键的自然顺序进行排序,或者通过在地图创建时提供的
Comparator
排序,具体取决于使用的构造函数。
树形图是红黑树,它是平衡的二叉搜索树 。 换句话说,树已经被排序(或者更确切地说,按照二进制搜索树规则排列),其高度平衡,使得树操作具有O(lg n)复杂度。 但是,我认为你想要的是按排序顺序打印所有键。 这就像在树形图上实现inorder遍历一样简单,或者您可以使用keySet()方法获取Set并迭代值。
例如,遍历遍历
void inorderTraversal( Node root ){ if( root == null ) return; inorderTraversal( root.getLeft() ); root.printValue(); inorderTraversal( root.getRight() ); }
编辑 :
好的,我很确定这就是你想要的。 您想按值排序:
Map map = new TreeMap(); map.put("one", 8); map.put("two", 10); map.put("three", 9); map.put("hundred", 1); System.out.println(map.values());
输出:
[1, 8, 9, 10]
所以这甚至适用于排序字符串值:
Map map = new TreeMap(); map.put(8, "one"); map.put(10, "two"); map.put(9, "three"); map.put(1, "hundred"); System.out.println(map.values());
输出:
[hundred, one, three, two]
另外,sachin注意到“变量键”和变量值是完全不同的东西。