【问题标题】:How to convert MutableMap to ObjectDoubleMap using Eclipse Collections?如何使用 Eclipse Collections 将 MutableMap 转换为 ObjectDoubleMap?
【发布时间】:2018-09-10 14:59:14
【问题描述】:

如何使用 Eclipse Collections 将 MutableMap<String, Double> 转换为 ObjectDoubleMap<String>

在我的用例中,我有一个可变映射,它是聚合结果。例如;

MutableMap<String, Double> map = list.aggregateBy(func, factory, aggregator);

我必须调用另一个只接受ObjectDoubleMap&lt;String&gt; 的方法,如何将map 转换为ObjectDoubleMap&lt;String&gt; 的类型?我别无选择,只能使用 Eclipse Collections 框架。

【问题讨论】:

    标签: java eclipse-collections


    【解决方案1】:

    首先,感谢您使用 Eclipse Collections!目前,将MutableMap 转换为ObjectDoubleMap 的最佳方法是使用forEachKeyValue() 进行迭代并将键值设置为空MutableObjectDoubleMap

    MutableMap<String, Double> stringDoubleMutableMap = Maps.mutable.with("1", 1.0, "2", 2.0);
    MutableObjectDoubleMap<String> targetMap = ObjectDoubleMaps.mutable.empty();
    stringDoubleMutableMap.forEachKeyValue((key, value) -> targetMap.put(key, value));
    

    将来我们可以考虑添加一个 API,这将使从 RichIterable&lt;BoxedPrimitive&gt;PrimitiveIterable 的转换更容易。

    随时使用您想要的 API 在Eclipse Collections GitHub Repo 上打开问题。这有助于我们跟踪用户的功能请求。 Eclipse Collections 也对贡献开放,请随时贡献您想要的 API:Contribution Guide

    来自 cmets 的更新答案,lambda 可以简化为方法参考:

    stringDoubleMutableMap.forEachKeyValue(targetMap::put);
    

    注意:我是 Eclipse Collections 的提交者。

    【讨论】:

    • 谢谢,这是为基元调整界面的冗长方式,但它仍然有效。
    • 就像我在回答中提到的,如果您觉得有一个转换 API,我们应该随时在我们的 GitHub 存储库上提出建议。另外,不要忘记接受答案。
    • 接受!有一个更简单的 API 会很好
    • 这可以使用方法引用而不是 lambda 稍微简化 - stringDoubleMutableMap.forEachKeyValue(targetMap::put);
    猜你喜欢
    • 2019-02-26
    • 2018-12-29
    • 2014-04-23
    • 2015-02-27
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2011-01-26
    相关资源
    最近更新 更多