如何在任何Java映射实现上测试空键? [英] How to test for null keys on any Java map implementation?
本文介绍了如何在任何Java映射实现上测试空键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想确保作为参数传递给方法的Map不包含空键。人们会假设以下情况会做到:
I would like to ensure that a Map being passed as an argument to a method doesn't include null keys. One would assume that the following would do:
if ( map.containsKey(null) ) …
,但是如果方法通过类似 TreeMap
这样的方法,则会中断每个常规Java Map合同的可以自由地使用NPE拒绝空键。
but that will break if the method is passed something like a TreeMap
, which per the general Java Map contract is free to reject null keys with a NPE.
在接受任何Map实现的同时,我们是否有一种明智的方法来测试空键?
Do we have a sensible way to test for null keys while accepting any Map implementation?
推荐答案
boolean hasAnyNull = yourMap.keySet()
.stream()
.anyMatch(Objects::isNull);
这篇关于如何在任何Java映射实现上测试空键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文