ist Ich habe ein List<Foo>
und will eine Guave Multimap<String, Foo>
, wo wir die Foo
‚s von jedem Tag ihrer Collection<String> getTags()
Funktion gruppiert haben.sauberste Art und Weise eine Sammlung durch eine Eigenschaft des Elements zu indizieren, dass ich eine Sammlung
Ich benutze Java 8, also lambdas und Methodenreferenzen sind gut/ermutigt.
Zum Beispiel, wenn ich:
foo1, tags=a,b,c
foo2, tags=c,d
foo3, tags=a,c,e
Ich würde eine bekommen Multimap<String, Foo>
mit:
Multimap<String, Foo> map = list.stream().collect(
ImmutableMultimap::builder,
(builder, value) -> value.getTags().forEach(tag -> builder.put(tag, value)),
(builder1, builder2) -> builder1.putAll(builder2.build())
).build();
Dieses:
a -> foo1, foo3
b -> foo1
c -> foo1, foo2, foo3
d -> foo2
e -> foo3
Seit Guava 21 gibt es eine integrierte [ImmutableListMultimap.toImmutableListMultimap] (https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/ImmutableListMultimap.html# toImmutableListMultimap-java.util.function.Function-java.util.function.Function-) collector. –