如何从 LinkedHashMap 中的特定键开始迭代?
有一个我知道的数据结构
Stock
{
String Symbol;
LinkedHashMap<Date,Double> DateForPrice;
}
如果我在 LinkedHashMap 中
,我可以获取特定日期的股票价格,而无需遍历整个列表。但是,如果我想从特定日期开始迭代 DateForPrice 的 LinkedHashMap,有什么方法可以在不遍历整个列表的情况下完成此操作?
If I have a data structure
Stock
{
String Symbol;
LinkedHashMap<Date,Double> DateForPrice;
}
I know in the LinkedHashMap, I can get the stock price of specific date without traversing the whole list.
However, if I want to iterate through the LinkedHashMap of DateForPrice starting from a specific date, are there any way to do it without traversing the whole list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
LinkedHashMap
不提供在地图数据的有序视图中间开始迭代的方法。假设您的用例确实需要某个Date d
之后的所有日期并迭代这些日期,那么您可能应该将地图存储为TreeMap
。这里的一个重要区别是LinkedHashMap
的排序是插入顺序,我们假设的用例是您想要自然的键顺序< /em>.TreeMap
维护这样一个视图,通过地图的键对地图的内容进行排序。TreeMap
的另一个好处是允许您根据键创建地图切片,因此您可以调用tailMap(K k)
,返回包含 < 之后出现的所有键的映射代码>k。在这种情况下,您可以使用起点d
调用tailMap
。例如:
tailMap
方法返回SortedMap
,它是不可迭代的。但它有返回Set
的entrySet
方法,它是Iterable
的子接口。方便的是,如果您想继续将数据存储在
LinkedHashMap
中,您可以简单地使用当前实例加载TreeMap
(当然,需要一些性能权衡):LinkedHashMap
doesn’t offer a way to start iterating in the middle of its ordered view of the map’s data. Supposing your use case is really that you want all dates after someDate d
and to iterate those, then you should probably store your map as aTreeMap
. An important distinction here is thatLinkedHashMap
’s ordering is the insertion-order, and our supposed use-case here is that you want the natural key-order.TreeMap
s maintain such a view, sorting the contents of the map by the map’s key.TreeMap
s have the additional benefit of allowing you to create slices of the map based on the key, so you can calltailMap(K k)
, to return the map with all keys occurring afterk
. In this case, you can calltailMap
with your starting point,d
.e.g.:
tailMap
method returnsSortedMap
, which is not iterable. But it hasentrySet
method returningSet
, which is subinterface ofIterable
.Conveniently, if you want to keep storing your data in a
LinkedHashMap
you can simply load up aTreeMap
with your current instance (with some performance tradeoff, of course):我建议使用
TreeMap
- 它将按日期排序,您可以使用tailMap
来获取所需的部分I'd suggest to use
TreeMap
instead - it will be sorted by date and you can usetailMap
to get the required portion