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…
If you’re using Java 6 or above, you can use
NavigableMapinstead ofSortedMap, and use itslastEntrymethod.Otherwise, you can use
SortedMap.get(SortedMap.lastKey()).