我想做以下事情:
List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
但是在某种程度上,结果列表是Guava的实现ImmutableList.
我知道我能做到
List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList());
List<Integer> immutableList = ImmutableList.copyOf(list);
Run Code Online (Sandbox Code Playgroud)
但是我想直接收集它.我试过了
List<Integer> list = IntStream.range(0, 7)
.collect(Collectors.toCollection(ImmutableList::of));
Run Code Online (Sandbox Code Playgroud)
但它引发了一个例外:
com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:96)中的java.lang.UnsupportedOperationException
我发现自己想要一个Collectors.toMap返回的变体ImmutableMap,这样我就能做到:
ImmutableMap result = list.stream().collect(MyCollectors.toImmutableMap(
tuple -> tuple._1(), tuple -> tuple._2());
Run Code Online (Sandbox Code Playgroud)
(tuple在这个特定的例子中是Scala Tuple2)
我刚刚了解到这样的方法将在Guava 21中使用Java-8支持(耶!)但这听起来好一个月之后.有谁知道今天可能实现的任何现有库(等)?
ImmutableMap并非严格要求,但似乎是我要求的最佳选择:按键查找,并保留原始迭代顺序.不变性也是首选.
请注意,这FluentIterable.toMap(Function)还不够,因为我既需要键映射功能,也需要值映射功能.
寻找一种简单的方法来收集KeyAndValues having fields - String and List<T>到ImmutableListMultimap<String,T>?试图做一些像,
Collector.of(
ImmutableListMultimap.Builder::new,
ImmutableListMultimap.Builder<String,List<T>>::putAll,
(b1, b2) -> b1.putAll(b2.build()),
(builder) -> builder.build());
Run Code Online (Sandbox Code Playgroud)
putAll需要Key,List<T>.我不知道如何在组合器中实现这一点.
编辑:
@Value(staticConstructor = "of")
private static class KeyAndValues<T> {
private final String key;
private final List<T> values;
}
Run Code Online (Sandbox Code Playgroud)