java - 为什么 Guava 不提供转换映射键的方法

标签 java guava

这个问题已经发布在这里: How to convert Map<String, String> to Map<Long, String> using guava

我觉得CollinD的回答很贴切:

All of Guava's methods for transforming and filtering produce lazy results... the function/predicate is only applied when needed as the object is used. They don't create copies. Because of that, though, a transformation can easily break the requirements of a Set.

Let's say, for example, you have a Map<String, String> that contains both "1" and "01" as keys. They are both distinct Strings, and so the Map can legally contain both as keys. If you transform them using Long.valueOf(String), though, they both map to the value 1. They are no longer distinct keys. This isn't going to break anything if you create a copy of the map and add the entries, because any duplicate keys will overwrite the previous entry for that key. A lazily transformed Map, though, would have no way of enforcing unique keys and would therefore break the contract of a Map.

这个是对的,但其实我不明白为什么不这样做是因为:

  • 当键转换发生时,如果 2 个键被“合并”,可能会引发运行时异常,或者我们可以传递一个标志来指示 Guava 为新计算的多个可能值取任何值关键(failfast/failsafe 可能性)

  • 我们可以有一个 Maps.transformKeys 来生成一个 Multimap

这样做有没有我看不到的缺点?

最佳答案

正如@CollinD 所建议的,没有办法以惰性方式执行此操作。实现get ,您必须使用转换函数转换所有键(以确保发现任何重复项)。

所以申请Function<K,NewK>Map<K,V>出来了。

您可以安全地申请 Function<NewK,K>到 map :

V value = innerMap.get( fn.apply(newK) );

我没有看到 Guava 的简写形式——它可能不够有用。您可以通过以下方式获得类似的结果:

Function<NewK,V> newFn = Functions.compose(Functions.forMap(map), fn);

关于java - 为什么 Guava 不提供转换映射键的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13991710/

相关文章:

java - 获取第一个值 TreeMultiMap

c# - 具有 Equals 和 GetHashCode 辅助方法的库,适用于 .NET

java - DispatcherServlet 未重定向到适当的 View

java - 获取美国各州列表的最简单方法

java - 使用 Guava Cache 作为 "helper"作为我自己的持久缓存是否可行?

java - 提供给 Google Guava 的 Preconditions.* 方法的正确错误消息是什么?

caching - Guava Cache 的 BiMap 功能?

可关闭的Java标签

java - 如何使用日期正则表达式的模式匹配器?

java - 责任链——处理多个请求