基于键对树图进行排序,其中键是变量
我想根据键对树图进行排序,其中键是变量,因此排序应该基于变量值,我们如何实现这一点?我想在内置排序方法中使用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
TreeMap
(它实现SortedMap
) 自动将密钥存储在正确的位置order:作为 Key-Type (在这种情况下
Integer
),您可以使用任何实现Comparable
(或者您可以提供Comparator
创建TreeMap
时)编辑:好的,这里是如何重新映射地图的建议。
TreeMap
(which implementsSortedMap
) stores automatically the keys in the correct order:As Key-Type (in that case
Integer
) you can use any class which implementsComparable
(or you can provide aComparator
when creating theTreeMap
)Edit: Okay, here is a suggestion how to re-map your map.
treemap 是一棵红黑树,这是一个平衡的二叉搜索树。换句话说,树已经排序(或者更确切地说,按照二叉搜索树规则排列),其高度平衡,因此树操作具有 O(lg n) 复杂度。但是,我认为您想要的是按排序顺序打印所有键。这就像在树形图上实现中序遍历一样简单,或者您可以使用 keySet() 方法来获取 Set 并迭代值。
例如中序遍历
编辑:
好的,我很确定这就是你想要的。您想按值排序:
输出:
所以这甚至适用于对字符串值进行排序:
输出:
另外,sachin 请注意,拥有“变量键”和变量值是完全不同的事情。
A treemap is a Red-black tree, which is a balanced binary search tree. In other words, the tree is already sorted (or rather, arranged as per the binary search tree rules) with its height balanced so that tree operations have a O(lg n) complexity. However, I think what you want is to print all the keys in sorted order. This is as simple as implementing an inorder traversal on the treemap, or you could use the keySet() method to get a Set and iterate over the values.
e.g. of inorder traversal
EDIT:
Okay, I'm pretty sure this is what you want. You want to sort by values:
Output:
So this works even for sorting string values:
Output:
Also, sachin take note that having "variable keys" and variable values are completely different things.
TreeMap
实现SortedMap
接口并按其键排序,而无需您做任何事:TreeMap
implements theSortedMap
interface and is sorted by its key without you having to do anything: