【发布时间】:2021-08-02 16:53:25
【问题描述】:
假设我有一张地图:Map<Int, String>,我知道这张地图是如何创建的,并且它保留了迭代的顺序。如何迭代给定范围内的所有元素?
val map: Map<Int, String> = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four")
// Let's say I want to get all values after key 3.
val iterator = map.iterator()
while (iterator.next().key != 3) {}
val itemsAfter3 = iterator.asSequence().map { it.value }
除了丑,就是O(n)。有没有更好、更优雅、更高效的方式?
我正在考虑用map.keys.indexOf() 做点什么,但这里的复杂性似乎也是线性的。
【问题讨论】:
-
Map-interface 不支持此功能,因此您要么必须使用不同的数据结构,要么直接使用 Map 实现类来实现它。 -
"it is O(n)" LinkedHashMap,则不能。
标签: kotlin collections iterator