java:地图视图隐藏带有空键的条目?
我有一个 Map
其中包含带有 null 键的特殊值。改变事情并不那么容易,所以我没有这个。
有没有办法执行以下任一操作:
- 制作此地图的视图,该地图也是隐藏空键条目的
Map
- 制作地图的
视图keySet()
隐藏空键条目
我所说的“视图”是指地图中的更改会导致视图中的更改。
我认为后者更容易,但我不知道该怎么做。
I have a Map<String,String>
which contains a special value with a null key. It's not so easy to change things so I don't have this.
Is there a way to do either of the following:
- make a view of this map that is also a
Map<String,String>
which hides the null-key entry - make a view of the map's
keySet()
which hides the null-key entry
By "view" I mean that changes in the map produce changes in the view.
I assume the latter is easier but I don't know how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果带有 null 键的值是一种特殊情况,并且不打算在访问条目时使用,那么为什么它会出现在映射中?您决定将其放入映射中而不是使用不同的字符串变量是否有原因?
听起来使用不同的方法会更容易,而不是尝试扩展地图以具有针对这种情况的一些特殊属性。这也将更明确地表明该字符串值是一个特殊值,而不是可能使未来的开发人员绊倒的东西,他们必须在您之后查看此代码。
If the value with the null key is a special case and not meant to be used when you access the entries, why is it in the map? Is there a reason why you decided to put it in the map instead of having different string variable?
It sounds like it would be easier to use a different approach instead of trying to extend the map to have some special properties for this one case. This would also would be more explicit in showing that this string value is a special value and not something that could trip up future developers who have to look at this code after you.
简单的方法是扩展您的映射并重写适当的方法来检查空键值。这些将是:
您还可以实现自己的扩展 Map 的对象,并在构造函数中传递带有 null 的 Map,并在调用上述方法之一时执行检查/控制。
如果您对外部库开放,您可以查看 谓词映射。
The simple method is to extend your map and override the proper methods to check for null key values. These would be:
You could also implement your own object extending Map and pass your Map-with-null in the constructor and perform check/controls when one of the above methods are called.
If you are open to external libraries, you could take a look at PredicatedMap.
我使用了 Guava 的
Maps.filterKeys()
;效果很好。I used Guava's
Maps.filterKeys()
; that worked fine.