Question

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.

Was it helpful?

Solution

Why would you be checking for nulls?

If you use the Google Collections Library you can use Iterables.limit.

EDIT: For some reason the GCL page doesn't include limit, but it's in Guava (which has effectively replaced the GCL) - it's still Iterables.limit.

OTHER TIPS

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
  }
}

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top