2

What is the idiomatic way to map a Collection<Foo> onto a MultiMap<A, B>? Were

public class Foo {
    public A key;
    public B val;
}

(This is simplified, of course.)

The way I can think to do it is to to use Collection::stream() to invoke MultiMap::put on each element, but I feel there might be a much more elegant way to do this.

And can a new MultiMap be returned with those mappings, all in one line?

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145

1 Answers1

2

Since version 21.0 onwards, the most idiomatic way to do this is to use one of the collectors already provided by Guava, in this case the one provided by the Multimaps.toMultimap utility method:

Multimap<A, B> result = foos.stream()
    .collect(Multimaps.toMultimap(Foo::getA, Foo::getB, ArrayListMultimap::create));

This creates an ArrayListMultimap, but of course you can create the concrete Multimap you want, either by using a factory method or one of Guava's specific builders.

fps
  • 33,623
  • 8
  • 55
  • 110