java:地图视图隐藏带有空键的条目?

发布于 2024-11-05 22:56:51 字数 321 浏览 0 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不离久伴 2024-11-12 22:56:51

如果带有 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.

留一抹残留的笑 2024-11-12 22:56:51

简单的方法是扩展您的映射并重写适当的方法来检查空键值。这些将是:

containsKey(Object key)
entrySet() 
get(Object key) 
keySet() 
put(K key, V value) 
putAll(Map<? extends K,? extends V> m) 

您还可以实现自己的扩展 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:

containsKey(Object key)
entrySet() 
get(Object key) 
keySet() 
put(K key, V value) 
putAll(Map<? extends K,? extends V> m) 

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.

凉风有信 2024-11-12 22:56:51

我使用了 Guava 的 Maps.filterKeys();效果很好。

 Maps.filterKeys(mymap, new Predicate<String>() {
    @Override public boolean apply(String key) { return key != null; } 
 }),

I used Guava's Maps.filterKeys(); that worked fine.

 Maps.filterKeys(mymap, new Predicate<String>() {
    @Override public boolean apply(String key) { return key != null; } 
 }),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文