我有一个 TreeMap< Long, Integer >;我想做的是找到具有特定长键的条目,然后迭代该特定键“之后”的所有条目。实际上,我想要的是 TreeMap.floorEntry(K key) 的变体,它将迭代器返回到 map 而不是 Map.Entry 中。有什么方法可以达到这种效果吗?
最佳答案
您需要使用SortedMap#tailMap(Object)
Returns a view of the portion of this map whose keys are greater than or equal to
fromKey
. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.
例如,
TreeMap<Long, Integer> m = new TreeMap<>();
m.put(1L, 1);
m.put(2L, 1);
m.put(3L, 1);
m.put(4L, 1);
m.put(5L, 1);
m.put(6L, 1);
m.put(7L, 1);
m.put(8L, 1);
System.out.println(m.tailMap(3L));
将打印原始映射中具有大于或等于键3L
的键的所有条目。
{3=1, 4=1, 5=1, 6=1, 7=1, 8=1}
tailMap
返回一个 SortedMap
。您可以将其分配给变量并用它执行您想要的操作,例如。获取其 entrySet
并迭代它。
关于java - 搜索树形图,然后按顺序迭代所有大于某个键的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111485/