获取 TreeMap 的最后 3 个值
我有一个日期/字符串 TreeMap,我想循环遍历最后 N 个条目。
TreeMap<Date,String> map = new TreeMap<Date,String>();
map.put(new Date(2011,1,1), "32,1");
map.put(new Date(2011,3,1), "35");
map.put(new Date(2011,4,5), "38,9");
map.put(new Date(2011,8,2), "57!!");
然后我就迷路了。我发现了这个:
NavigableSet<Date> dates = donnees.descendingKeySet();
然后我不知道该怎么说:
for(key in dates and i ; i from 0 to N)
{ do something }
有帮助吗?
I have a Date/String TreeMap and I want to loop through the N last entries.
TreeMap<Date,String> map = new TreeMap<Date,String>();
map.put(new Date(2011,1,1), "32,1");
map.put(new Date(2011,3,1), "35");
map.put(new Date(2011,4,5), "38,9");
map.put(new Date(2011,8,2), "57!!");
Then I'm lost. I've found this :
NavigableSet<Date> dates = donnees.descendingKeySet();
Then I don't know how to say something like :
for(key in dates and i ; i from 0 to N)
{ do something }
Any help ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
看起来您想迭代
descendingMap()
:控制台:
附录:以下是在默认区域设置中使用
Calendar
的示例:It looks like you want to iterate though the
descendingMap()
:Console:
Addendum: Here's an example using
Calendar
in the default locale:或者(等效):
Or (equivalent):
你关心树的状态吗?如果没有,那么您可以执行 pollLastEntry()。这将从树上删除最后一个条目并将其交给您。做3次就完成了。或者您可以将树展平为 arrayList 并只返回最后 3 个元素。
Do you care about the state of the tree? If not, then you could do pollLastEntry(). This will remove the last entry off the tree and give it to you. Do 3 times and you're done. Or you could flatten the tree into an arrayList and just return the last 3 elements.
听起来您只需要循环遍历前三个项目:
Sounds like you just need to loop through the items for the first three:
“最后 3”因为它是从后到前的。
您可以只实现 Comparator 并将其传递给 TreeMap,以便“最旧”的日期位于 TreeMap 的头部。
the "last 3" because it is back to front.
You could just implement Comparator and pass it to the TreeMap so the "oldest" dates are at the head of the TreeMap.
TreeMap 到 Array 并使用 for 循环读取数组,条件为 i < 3
TreeMap to Array and read the array with a for loop with the condition i < 3