Is it possible to extract the top n (I use top because I believe a TreeMap is sorted) key elements from a TreeMap, without iterating using an Iterator object.
I can do the iteration but it's tedious to have to check for nulls etc.
Is it possible to extract the top n (I use top because I believe a TreeMap is sorted) key elements from a TreeMap, without iterating using an Iterator object.
I can do the iteration but it's tedious to have to check for nulls etc.
Why would you be checking for nulls?
If you use the Google Collections Library you can use Iterables.limit.
you can use:
[subMap method][1]
public NavigableMap<K,V> subMap(K fromKey,boolean fromInclusive,K toKey,boolean toInclusive)
[1]: http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html#subMap(K, boolean, K, boolean)
I've noticed that you have already asked this question here: http://stackoverflow.com/questions/577358/easy-way-to-get-a-subset-of-the-keyset-of-a-treemap-in-java where you've already got some answers.
You can easily get the subset of keys from one key up to another using .subMap(low,high).keySet()
or .headMap(high).keySet()
.
Finding out the correct high key for the nth is harder, as there is no direct approach and iterating is the only sure-fire way.
(this code is untested)
public <K,V> SortedMap<K,V> subMap(SortedMap<K,V> map, int n) {
Iterator<K> it = map.keySet().iterator();
for (int i = 0; i<n && it.hasNext(); i++) {
it.next();
}
if (it.hasNext()) {
return map.headMap(it.next());
} else {
return map
}
}