Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last n elements of a Treemap

Tags:

java

treemap

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

like image 909
Nikolaus Hartlieb Avatar asked Dec 21 '11 11:12

Nikolaus Hartlieb


2 Answers

use TreeMap.tailMap() for it.

like image 138
amit Avatar answered Oct 23 '22 04:10

amit


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));
like image 28
Jon Skeet Avatar answered Oct 23 '22 04:10

Jon Skeet