Java 8 Guava 的 ImmutableListMultimap 收集器<String,T>

Java 8 Collector for Guava's ImmutableListMultimap<String,T>

正在寻找一种将 KeyAndValues having fields - String and List<T> 中的 collection 收集到 ImmutableListMultimap<String,T> 的简单方法? 试图做类似的事情,

 Collector.of(
          ImmutableListMultimap.Builder::new,
          ImmutableListMultimap.Builder<String,List<T>>::putAll,
          (b1, b2) -> b1.putAll(b2.build()),
          (builder) -> builder.build());

putAll 占用 KeyList<T>。我不确定如何在组合器中实现这一点。

编辑:

 @Value(staticConstructor = "of")
 private static class KeyAndValues<T> {

    private final String key;
    private final List<T> values;
}

不确定 KeyAndValues<T> 上可用的方法,但是这个怎么样?

  public static <T> Collector<KeyAndValues<T>,
                              ImmutableListMultimap.Builder<String, T>, 
                              ImmutableListMultimap<String, T>> toImmutableMultimap()
  {
    return Collector.of(
        ImmutableListMultimap.Builder::new,
        (b, kav) -> b.putAll(kav.getKey(), kav.getValues()),
        (builder1, builder2) -> builder1.putAll(builder2.build()),
        (builder) -> builder.build());
  }

或者,如果您希望隐藏累加器的详细信息,您可以使用如下方式:

public static <T> Collector<KeyAndValues<T>,
                            ?,
                            ImmutableListMultimap<String, T>> toImmutableMultimap()
{
  return Collector.of(
    ImmutableListMultimap.Builder<String, T>::new,
    (b, kav) -> b.putAll(kav.getKey(), kav.getValues()),
    (builder1, builder2) -> builder1.putAll(builder2.build()),
    (builder) -> builder.build());
}