Multimaps.index() 但生成 NavigableMap?
我需要有效的 ImmutableNavigableListMultimap
,其中 HasOffset
看起来像:
interface HasOffset {
public int getOffset();
}
但是没有 ImmutableNavigableListMultimap
:我想要的是一个不可变的NavigableMap
,我从 List
创建,其中我通过偏移量对每个 HasOffset
进行索引。例如,如果我有这些对象:
115 Elm St. John Smith
115 Elm St. Jane Smith
108 Elm St. Thomas Little
101 Elm St. Bill Jones
115 Elm St. Buster Smith
112 Elm St. Mary Kay
101 Elm St. Judy Jones
那么我想要的是一个 Map,它看起来像
101 -> [Bill Jones, Judy Jones]
108 -> [Thomas Little]
112 -> [Mary Kay]
115 -> [John Smith, Jane Smith, Buster Smith]
我可以使用键并找到该键下方或上方最近的值。
番石榴可以帮忙还是我只能自己做?我喜欢 Multimaps.index()
但我认为这次它对我没有帮助。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Guava 仍然是一个 Java 5 库,因此您不会在其中找到任何实现
Navigable*
的内容。如果你真的想要,你可以通过首先对 Multimaps.index() 的输入进行排序,然后使用 ImmutableListMultimap 的 keySet( ).asList() 查看并对键进行二分搜索并利用它返回的索引。但这显然不一样。
另一种选择可能是使用 Multimaps.index() 来消除创建地图的乏味,然后将其 asMap() 视图复制到 TreeMap< ;整数,集合>。显然,与自己做相比,还有一些额外的工作要做。
Guava is still a Java 5 library so you aren't going to find anything implementing
Navigable*
in it.If you really wanted, you could kinda sorta fake this by first sorting the input to
Multimaps.index()
and then making use of theImmutableListMultimap
'skeySet().asList()
view and doing a binary search for a key and making use of the index it returns. But that's not the same obviously.Another option perhaps would be to use
Multimaps.index()
to take out the tedium of creating the map and then copy itsasMap()
view in to aTreeMap<Integer, Collection<HasOffset>>
. Obviously there's some extra work going on there compared to just doing it yourself.您可以创建一个
TreeMultimap
,它具有返回SortedSet
的keySet()
方法。那么小于给定键的最大键是
multimap.keySet().headSet(key).last()
,而大于或等于给定键的最小键是multimap。 keySet().tailSet(key).first()
。您可以确定这两个键中的哪一个更接近输入键,并从多重映射中检索其值。您必须处理输入键小于所有多重映射键或大于所有多重映射键的情况。当头集或尾集为空时,
last()
和first()
方法会抛出NoSuchElementException
。You could create a
TreeMultimap
, which has akeySet()
method returning aSortedSet
.Then the largest key less than a given key is
multimap.keySet().headSet(key).last()
, while the smallest key greater than or equal to a given key ismultimap.keySet().tailSet(key).first()
. You could determine which of those two key is closer to the input key and retrieve its values from the multimap.You'll have to handle the cases in which the input key is smallest than all multimap keys or larger than all of them. When the head set or tail set is empty, the
last()
andfirst()
methods throw aNoSuchElementException
.