How to get last n elements of a Treemap

…衆ロ難τιáo~ 提交于 2019-12-10 14:21:13

问题


I have a TreeMap, that looks like this:

 TreeMap<Instant, HashMap<Type, Double>>

The Instant values are representing hours of a day; for each passed hour a value is stored in my map. Now I would like to get the last 24 elements (so the hours of the passed day) of this map. How could I do that?

Cheers


回答1:


You can use the descendingMap call to get a view on the map which is basically in the reverse order, then take the first 24 entries from that (call iterator etc). (Guava's Iterables provides helpful methods for limiting an iterable etc.)

EDIT: For example, to get the last 24 elements (in reverse order, and using Guava) you could use:

List<HashMap<Type, Double>> lastValues = Lists.newArrayList
    (Iterables.limit(map.descendingMap().values(), 24));



回答2:


use TreeMap.tailMap() for it.




回答3:


You could make it a SortedMap<LocalDate, SortedMap<Hours, Map<Type, Double>>> so you can get the latest date from the outer Map.



来源:https://stackoverflow.com/questions/8588902/how-to-get-last-n-elements-of-a-treemap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!