开发者

Multimaps.index() but producing a NavigableMap?

开发者 https://www.devze.com 2023-02-21 10:51 出处:网络
I need what is effectively an ImmutableNavigableListMultimap<Integer, HasOffset> where HasOffset looks like:

I need what is effectively an ImmutableNavigableListMultimap<Integer, HasOffset> where HasOffset looks like:

interface HasOffset {
   public int getOffset();
}

But there is no ImmutableNavigableListMultimap: what I want is an immutable NavigableMap<Integer, List<HasOffset>> that I create from a List<HasOffset> where I index each HasOffset by its offset. For example, if I had these objects:

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

then what I want is a Map that looks like

101 -> [Bill Jones, Judy Jones]
108 -> [Thomas Little]
112 -> [Mary Kay]
115 -开发者_StackOverflow> [John Smith, Jane Smith, Buster Smith]    

where I can use a key and find the nearest values below or above that key.

Can Guava help or am I stuck doing it myself? I like Multimaps.index() but I don't think it can help me this time.


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 the ImmutableListMultimap's keySet().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 its asMap() view in to a TreeMap<Integer, Collection<HasOffset>>. Obviously there's some extra work going on there compared to just doing it yourself.


You could create a TreeMultimap, which has a keySet() method returning a SortedSet.

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 is multimap.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() and first() methods throw a NoSuchElementException.

0

精彩评论

暂无评论...
验证码 换一张
取 消