Search code examples
javacollectionsguavamultimap

How to use NavigableMap features with Guava's Multimap (with asMap())?


Let's assume i have something like this:

Multimap<Integer, Integer> data = TreeMultimap.create();

How can i use .headMap() on my data? I suppose, that TreeMultimap.asMap() is the way to go.

The documentation (link) says, that TreeMap.asMap() returns NavigableMap<K,Collection<V>>, but i'm not able to get that to work.

NavigableMap<Integer, ArrayList<Integer>> test = data.asMap(); // type mismatch
SortedMap<Integer, ArrayList<Integer>> test = data.asMap(); // type mismatch

What am i doing wrong?

Thanks!

PS: I'm using guava 16


Solution

  • The type of data is Multimap, not TreeMultimap. Also, a NavigableMap<Integer, Collection<Integer>>, is not compatible with NavigableMap<Integer, ArrayList<Integer>>.

    Change your code to:

    TreeMultimap<Integer, Integer> data = TreeMultimap.create();
    NavigableMap<Integer, Collection<Integer>> test = data.asMap();