HashMap 为未找到的键返回默认值?
是否可以让 HashMap
为集合中未找到的所有键返回默认值?
Is it possible to have a HashMap
return a default value for all keys that are not found in the set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
在 Java/Kotlin 混合项目中,还可以考虑 Kotlin 的 Map.withDefault 。
请参阅从 Java 访问 Kotlin 扩展函数。
In mixed Java/Kotlin projects also consider Kotlin's Map.withDefault.
See Accessing Kotlin extension functions from Java.
在 Java 8 中,使用 Map。 getOrDefault。它需要键,如果没有找到匹配的键,则返回值。
In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.
[更新]
正如其他答案和评论者所指出的,从 Java 8 开始,您可以简单地调用
Map#getOrDefault(...)
。[原始]
没有 Map 实现可以完全做到这一点,但通过扩展 HashMap 来实现您自己的实现将是微不足道的:
[Update]
As noted by other answers and commenters, as of Java 8 you can simply call
Map#getOrDefault(...)
.[Original]
There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:
使用 Commons 的 DefaultedMap 如果您不想重新发明轮子,例如,
如果您不负责创建地图,您也可以传入现有地图。
Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g.,
You can also pass in an existing map if you're not in charge of creating the map in the first place.
Java 8 引入了一个很好的 computeIfAbsent
Map
接口的默认方法,它存储延迟计算的值,因此不会破坏地图契约:起源:http://blog.javabien.net/2014/ 02/20/loadingcache-in-java-8-without-guava/
免责声明:
这个答案与OP所要求的不完全匹配,但在某些情况下,当键数量有限并且缓存不同值会有利可图时,匹配问题的标题可能会很方便。它不应该在具有大量键和相同默认值的相反情况下使用,因为这会不必要地浪费内存。
Java 8 introduced a nice computeIfAbsent default method to
Map
interface which stores lazy-computed value and so doesn't break map contract:Origin: http://blog.javabien.net/2014/02/20/loadingcache-in-java-8-without-guava/
Disclamer:
This answer doesn't match exactly what OP asked but may be handy in some cases matching question's title when keys number is limited and caching of different values would be profitable. It shouldn't be used in opposite case with plenty of keys and same default value as this would needlessly waste memory.
难道你不能创建一个静态方法来完成这个任务吗?
Can't you just create a static method that does exactly this?
您可以简单地创建一个继承HashMap的新类并添加getDefault方法。
这是一个示例代码:
我认为您不应该在实现中重写 get(K key) 方法,因为 Ed Staub 在他的评论中指定的原因,并且因为您将破坏 Map 接口的契约(这可能会导致一些难以理解的问题) - 查找错误)。
You can simply create a new class that inherits HashMap and add getDefault method.
Here is a sample code:
I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).
在 Java 8+ 上
On java 8+
使用:
Use:
它默认执行此操作。它返回
null
。It does this by default. It returns
null
.我找到了 LazyMap 非常有帮助。
这允许您执行如下操作:
对
get
的调用为给定键创建默认值。您可以指定如何使用LazyMap.lazyMap(map, factory)
的工厂参数创建默认值。在上面的示例中,映射被初始化为值为 0 的新AtomicInteger
。I found the LazyMap quite helpful.
This allows you to do something like this:
The call to
get
creates a default value for the given key. You specify how to create the default value with the factory argument toLazyMap.lazyMap(map, factory)
. In the example above, the map is initialized to a newAtomicInteger
with value 0.不直接,但您可以扩展该类来修改其 get 方法。这是一个随时可用的示例: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm
Not directly, but you can extend the class to modify its get method. Here is a ready to use example: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm
用法示例:
Example Usage:
我需要读取从服务器返回的 JSON 格式的结果,但我无法保证字段会存在。我正在使用派生自 HashMap 的 org.json.simple.JSONObject 类。以下是我使用的一些辅助函数:
I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:
HashMap会导致死循环,所以使用ConcurrentHashMap代替HashMap,
HashMap cause dead loop, so use ConcurrentHashMap instead of HashMap,
在使用getOrDefault方法的地图中,如果找不到键,我们可以将默认值放在右侧参数中。
通过对状态进行分组,将列表转换为地图。
输出:
如您在上面的输出中看到的,未找到状态INPROGRESS,因此将默认值设置为0
In Map Using getOrDefault method if key is not found we can place the default value in right side parameter.
Converting List to Map by doing grouping Status.
OutPut:
As you see in the above output Status INPROGRESS is not found, so it takes Default value as 0