I have a TreeMap<Date, Integer>
and I want to fetch the nth item from that map. What I came up with now is this:
((Integer)myTreeMap.values().toArray()[index]).intValue();
but this feels quite clunky, not to mention what is happening on the heap or with performance?
Is there a concise way to get the nth item from a TreeMap
/SortedMap
?
Edit: an alternative is
final Optional<T> first =
treeMap.values()
.stream()
.skip(index - 1)
.findFirst();
if (first.isPresent()) {
final T value = first.get();
}
What about
final List<T> values = new ArrayList<>(myTreeMap.values());
final T value = values.get(index);
T
is just a generic type in place of your Map
value type.
index
is your nth element.
As pointed out, that's inefficient for large maps, as internally the ArrayList
constructor the toArray
method is called
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}