Reputation: 26273
I have a SortedMap
(a TreeMap
, specifically), from which I extract the values. Later, I need to get the first and last values, as they were ordered in the SortedMap
.
SortedMap.values()
returns a Collection
, whose Iterator
preserves order. Therefore, getting the first value is as simple as collection.iterator().next()
. However, getting the last value is not so simple -- iterating all the way through to get to the last is very inefficient.
Is there a way around this? For now, I'm iterating all the way to the end and storing that value, so I only have to do it once...
Upvotes: 2
Views: 141
Reputation: 198211
If you're using Java 6 or above, you can use NavigableMap
instead of SortedMap
, and use its lastEntry
method.
Otherwise, you can use SortedMap.get(SortedMap.lastKey())
.
Upvotes: 4