Search code examples
javaguava

guava multimap that uses TreeMap not HashMap?


I have something like the following:

final SortedMap<Integer,List<Integer>> m = new TreeMap<Integer,List<Integer>>();

And I'd like to use google-guava to make this a multimap. However I don't see any implementation that provides a SortedMap holding an ArrayList. I only see HashMap+ArrayList implementation (ArrayListMultimap). Does the implementation that I want exist?


Solution

  • Guava has a TreeMultimap that stores both keys and values in sorted order. However, this uses a TreeSet for the values rather than a List so it may not quite be what you want here. In that case, Guava allows you to create a Multimap that works any way you want using one of the Multimaps.new*Multimap methods, such as Multimaps.newListMultimap. To make one that works like you describe, you'd just write this:

    Map<Integer, Collection<Integer>> map = Maps.newTreeMap();
    ListMultimap<Integer, Integer> m = Multimaps.newListMultimap(map,
        new Supplier<List<Integer>>() {
          public List<Integer> get() {
            return Lists.newArrayList(); // assuming you want to use ArrayList
          }
        });