Search code examples
javagenericsguava

Compact way to create Guava Multimaps?


If I want to create a new Multimap with simple defaults, I curently need to do something like:

private final Multimap<Key, Value> providersToClasses = Multimaps
        .newListMultimap(
                new HashMap<Key, Collection<Value>>(),
                new Supplier<List<Value>>() {
                    @Override
                    public List<Value> get() {
                        return Lists.newArrayList();
                    }
                });

...because Java can't infer the correct types if Maps.newHashMap is used for the backing map. Of course, this can be refactored into a separate method, but is there already a way to write it more concisely?


Solution

  • The Guava documentation states that the create method advocated by some other answers "will soon be deprecated" in favour of the different forms presented below, and should therefore be avoided.

    From Guava 21.0 onwards, the recommended way of creating a Multimap object where values are stored in ArrayList collections is the following:

    MultimapBuilder.hashKeys().arrayListValues().build();
    

    You can also use parameters if you want to specify the expected number of keys in your map and the expected number of values per key:

    MultimapBuilder.hashKeys(expectedKeys).arrayListValues(expectedValuesPerKey).build();
    

    Finally, you can create a new Multimap from an existing one using this construct:

    MultimapBuilder.hashKeys().arrayListValues().build(multimap);
    

    If you want to use data structures other than ArrayLists in your Multimap, you can replace the call to arrayListValues() by a number of other ones, listed here.