简体   繁体   English

Java:使用空键隐藏条目的地图视图?

[英]java: Map view that hides the entry with a null key?

I have a Map<String,String> which contains a special value with a null key. 我有一个Map<String,String> ,其中包含一个带有空键的特殊值。 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 对该地图进行查看,该视图也是Map<String,String> ,它隐藏了空键项
  • make a view of the map's keySet() which hides the null-key entry 查看地图的keySet() ,它隐藏了空键条目

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. 我认为后者更容易,但我不知道该怎么做。

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. 您还可以实现扩展Map的自己的对象,并在构造函数中传递null的Map,并在调用上述方法之一时执行检查/控制。

If you are open to external libraries, you could take a look at PredicatedMap . 如果您对外部库开放,则可以看看PredicatedMap

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? 如果带有null键的值是特殊情况,并且在访问条目时不打算使用,那么为什么在映射中呢? 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. 在显示此字符串值是一个特殊值时,这也将更加明确,而不会使将来不得不在您之后看此代码的开发人员感到困惑。

I used Guava's Maps.filterKeys() ; 我用了番石榴的Maps.filterKeys() ; that worked fine. 效果很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM