Search code examples
javalistdictionaryguava

Java: a sorted multimap which is a map of lists and not a map of sets


I am looking for a sorted multimap, where a single key can be mapped to multiple values, no matter what is returned by equals() of these values. Thus, it should not be something like this:

import com.google.common.collect.*;

public class Test {
    public static void main(String[] args) {
        Multimap<Double, String> multimap = TreeMultimap.create();
        multimap.put(3.0, "a");
        multimap.put(3.0, "a");
        multimap.put(2.0, "b");
        // prints "b", "a"
        for(String s : multimap.values())
            System.out.println(s);
    }
}

I have always been using java.util.Map<Key, List<Value>> but it comes with a bit of boilerplate.

One of the possibilities is a parameterised type:

public class SortedMapOfLists<K, V> {
    SortedMap<K, List<V>> map = new TreeMap<>();
    public void put(K key, V value) {
        List<V> list = map.get(key);
        if(list == null) {
            list = new ArrayList<>();
            map.put(key, list);
        }
        list.add(value);
    }
    public List<V> values() {
        List<V> values = new ArrayList<>();
        for(List<V> list : map.values())
            for(V value : list)
                values.add(value);
        return values;
    }
}

but this implementation has a limited functionality.


Solution

  • It sounds like you're looking for MultimapBuilder.treeKeys().arrayListValues().build().