简体   繁体   English

获取TreeMap的键集的子集的简单方法(使用Java)

[英]Easy way to get a subset of the keyset of a TreeMap (in Java)

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. 是否可以从TreeMap中提取前n个键元素(我使用top是因为我相信TreeMap已排序),而无需使用Iterator对象进行迭代即可。

I can do the iteration but it's tedious to have to check for nulls etc. 我可以进行迭代,但是必须检查null等很繁琐。

Why would you be checking for nulls? 为什么要检查空值?

If you use the Google Collections Library you can use Iterables.limit . 如果您使用Google Collections Library ,则可以使用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 . 编辑:由于某些原因,GCL页面不包含limit ,但是它位于Guava中 (已有效替换了GCL)-仍然是Iterables.limit

You can easily get the subset of keys from one key up to another using .subMap(low,high).keySet() or .headMap(high).keySet() . 您可以使用.subMap(low,high).keySet().headMap(high).keySet()轻松地从一个键到另一个键获取键子集。

Finding out the correct high key for the n th is harder, as there is no direct approach and iterating is the only sure-fire way. 找出第n个正确的高键比较困难,因为没有直接的方法,而迭代是唯一可行的方法。

(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] [subMap方法] [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) [1]: http : //java.sun.com/javase/6/docs/api/java/util/TreeMap.html#subMap (K,boolean,K,boolean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM