Abhay
Abhay

Reputation: 139

Iterating through a Java Map within a range

I have a TreeMap<LocalDate, TreeSet<EmployeeObject> which contains Date as key and a Set of all employee whose birth date it is. I want to iterate this Map between two dates e.g 22/02/15 to 27/02/15. Is it possible to do it efficiently without having to traverse the whole Map?

(EDIT)Additional Question: As an alternate do you think a Trie or some other data structure is a better fit for this situation than a Map in storing birth dates for all employees and then later querying them between a range?

Upvotes: 0

Views: 206

Answers (2)

Zielu
Zielu

Reputation: 8552

Use TreeMap as the implementation (or import data to it). It will give you access to NavigableSet for keys, or subMap view of the Map within the requested range (which you can iterate normally). They are views so the data are not duplicated.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100040

It depends entirely on what sort of map you use. If you use a HashMap, no. If you use a TreeMap, yes (see the NavigableMap interface which it implements). If you use a Guava RangeMap, especially yes.

Upvotes: 2

Related Questions