Java - 是否有任何Stream收集器返回ImmutableMap? [英] Java - Are there any Stream Collectors that return ImmutableMap?

查看:267
本文介绍了Java - 是否有任何Stream收集器返回ImmutableMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己想要一个 Collectors.toMap 的变体,它返回一个 ImmutableMap ,这样我就可以:

I find myself wanting a variant of Collectors.toMap which returns an ImmutableMap, such that I can do:

ImmutableMap result = list.stream().collect(MyCollectors.toImmutableMap(
    tuple -> tuple._1(), tuple -> tuple._2());

(其中元组在这个特定的例子中是Scala Tuple2

(where tuple in this particular example is a Scala Tuple2)

我< a href =https://groups.google.com/forum/#!topic/guava-discuss/ZRmDJnAq9T0\"rel =noreferrer>刚刚学会了这样的方法将会带来Java-8支持在Guava 21(yay!)但这听起来好了6个月之后。有谁知道今天可能实现的任何现有库(等)?

I've just learned that such a method will be coming with Java-8 support in Guava 21 (yay!) but that sounds a good 6 months away. Does anyone know of any existing libraries (etc) which might implement this today?

ImmutableMap 并不是严格要求的,但似乎是我要求的最佳选择:按键查找,并保留原始迭代顺序。不变性也是首选。

ImmutableMap is not strictly required but seems the best choice as I require: lookup by key, and retaining original iteration order. Immutability is always preferred too.

请注意 FluentIterable.toMap(功能离子)是不够的,因为我既需要键映射功能,也需要值映射功能。

Note that FluentIterable.toMap(Function) is not sufficient because I need both a key-mapping function as well as a value-mapping function.

推荐答案

您不需要为此收集器编写匿名类。您可以使用 Collector.of 代替:

You don't need to write an anonymous class for this collector. You can use Collector.of instead:

public static <T, K, V> Collector<T, ?, ImmutableMap<K,V>> toImmutableMap(
            Function<? super T, ? extends K> keyMapper,
            Function<? super T, ? extends V> valueMapper) {
    return Collector.of(
               ImmutableMap.Builder<K, V>::new,
               (b, e) -> b.put(keyMapper.apply(e), valueMapper.apply(e)),
               (b1, b2) -> b1.putAll(b2.build()),
               ImmutableMap.Builder::build);
}

或者如果您不介意首先将结果收集到可变地图中,然后将数据复制到不可变的映射中,您可以使用内置的 toMap 收集器与 collectAndThen

Or if you don't mind collecting the results into a mutable map first and then copy the data into an immutable map, you can use the built-in toMap collector combined with collectingAndThen:

ImmutableMap<String, String> result = 
     list.stream()
         .collect(collectingAndThen(
             toMap(
                 tuple -> tuple._1(), 
                 tuple -> tuple._2()),
             ImmutableMap::copyOf));

这篇关于Java - 是否有任何Stream收集器返回ImmutableMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆