Java 中存储预排序键值对的内置方法?
我正在寻找一种方法来维护键值对的排序。它们按实际键值对之外的变量排序(为了更好的 UI)。我目前正在使用 Hashtable,但这并不维护排序 =(
Hashtable<Integer, String> subscriptions = getUsersSubscriptions(user);
Java 是否有一些简单的方法可以让一个存储对?我能想到的最好的想法是使用 2 个关联的 ArrayList (一个是整数类型,另一个是字符串类型)有人能想到更好的东西吗?
I'm looking for a way to maintain the sorting on my key-value pairs. They are sorted by variables outside of the actual key-value pairs (for better UI). I am currently using a Hashtable, but that does not maintain the sorting =(
Hashtable<Integer, String> subscriptions = getUsersSubscriptions(user);
Is there some simple way that Java lets one store pairs? The best idea I can think of is using 2 associated ArrayLists (one of type Integer, another of type String). Can someone think of something better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的键值对已排序,LinkedHashMap 将保持插入顺序。
换句话说,
map.keySet()
返回的键将按照您将它们放入地图中的确切顺序排列。If your key-value pairs are already sorted, LinkedHashMap will maintain order of insertion.
In other words, the keys returned by
map.keySet()
will be in the exact order you put them into the map.如果您有自定义排序,请传递
Comparator
实例到TreeMap
。但这样做要小心,因为使用与自然整数顺序不相符的比较器会使事情变得难以理解和调试。If you have a custom sorting, pass a
Comparator
instance to the constructor of theTreeMap
. But be careful doing so, as using a Comparator that does not go well with natural Integer order would make things impossible to understand and debug.这里可以使用LinkedHashMap。
LinkedHashMap can be used here.
创建一个存储这两个属性的自定义类。
为排序数据添加第三个属性。
然后您的类可以实现 Comparable 以根据此属性根据需要对数据进行排序。
或者您可以使用自定义比较器对排序数据字段进行排序。
现在类实例可以存储在 ArrayList 中。
Create a custom class that stores the two properties.
Add a third property for the sort data.
Then your class can implement Comparable to sort the data as required based on this property.
Or you can use a custom Comparator to sort on the sort data field.
Now the class instances can be stored in an ArrayList.