【问题标题】:Transform Map to object using Guava?使用番石榴将地图转换为对象?
【发布时间】:2013-03-22 16:50:07
【问题描述】:

使用 Guava,是否可以将 Map 转换为包含 Map 的键和值的对象的 Set 或 List?例如。给定类似的东西

class MyEntry {
    public String key;
    public String value;
}

Map<String,String> theMap = new Map<String,String>();

我在番石榴中缺少类似的东西/没有找到它:

Set<MyEntry> myEntries = Maps.transform(theMap, transformFunction<<Map<String,String>, MyEntry>);

显然手动执行此操作并不难,但我仍然想知道我是否遗漏了什么,而 Guava 真的不支持这样的事情?

感谢任何提示!

【问题讨论】:

    标签: java object map guava


    【解决方案1】:

    你可以用 Guava 做的最接近的事情就是

    Collection<MyEntry> myEntries = Collections2.transform(map.entrySet(), function);
    

    这只是对mapentrySet 的正常转换,而function 的类型为Function&lt;Map.Entry&lt;String, String&gt;, MyEntry&gt;

    Guava 不能提供Sets.transform 的原因有很多——它不能保证函数是单射的,它没有函数的逆函数等等。如果你需要一个Set,那么你最好只做手动循环。

    【讨论】:

    • 巧妙的“把戏”,我太专注于 Maps 类,没有想到 map.entrySet() 方法。感谢您的提示 :-) 甚至应该可以将其与 FluentIterable 一起使用,这是我的首选方式 :-)
    猜你喜欢
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多