Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

guava multimap that uses TreeMap not HashMap?

Tags:

java

guava

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?

like image 401
Kevin Avatar asked Jun 24 '11 15:06

Kevin


2 Answers

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
      }
    });
like image 191
ColinD Avatar answered Sep 28 '22 05:09

ColinD


Here's how you can create that beast:

Multimap<Integer,Integer> multimap = Multimaps.newListMultimap(
    Maps.<Integer, Collection<Integer>>newTreeMap(),
    new Supplier<List<Integer>>() {
        public List<Integer> get() {
            return Lists.newArrayList();
        }
    });
like image 21
Sean Patrick Floyd Avatar answered Sep 28 '22 07:09

Sean Patrick Floyd