How to get the last n Treemap elements

I have a TreeMap that looks like this:

TreeMap<Instant, HashMap<Type, Double>> 

Instantaneous values ​​are hours of the day; for each past hour, the value is saved on my map. Now I would like to get the last 24 elements (so the hours of the past day) of this card. How can i do this?

Greetings

+4
source share
3 answers

You can use the descendingMap call to get the view on the map, which is basically in the reverse order, and then take the first 24 entries from that (call iterator , etc.). ( Guava Iterables provides useful methods to limit iterable, etc.)

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

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

use TreeMap.tailMap () for this.

+3
source

You can do this SortedMap<LocalDate, SortedMap<Hours, Map<Type, Double>>> so that you can get the latest date from the external Map .

0
source

Source: https://habr.com/ru/post/1387366/


All Articles