问题
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