[英]Easy way to get a subset of the keyset of a TreeMap (in Java)
是否可以從TreeMap中提取前n個鍵元素(我使用top是因為我相信TreeMap已排序),而無需使用Iterator對象進行迭代即可。
我可以進行迭代,但是必須檢查null等很繁瑣。
為什么要檢查空值?
如果您使用Google Collections Library ,則可以使用Iterables.limit 。
編輯:由於某些原因,GCL頁面不包含limit
,但是它位於Guava中 (已有效替換了GCL)-仍然是Iterables.limit
。
您可以使用.subMap(low,high).keySet()
或.headMap(high).keySet()
輕松地從一個鍵到另一個鍵獲取鍵子集。
找出第n個正確的高鍵比較困難,因為沒有直接的方法,而迭代是唯一可行的方法。
(此代碼未經測試 )
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
}
}
您可以使用:
[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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.