I have a HashMap
with hundred of key/value pairs.
我有一个包含数百个键/值对的HashMap。
Now I have to delete all key/values except 2 key/value. I have use this way :
现在我必须删除除2键/值以外的所有键/值。我用这种方式:
if(map!=null){
String search = map.get(Constants.search);
String context = map.get(Constants.context);
map = new HashMap<>();
map.put(Constants.search,search);
map.put(Constants.context,context);
}
But java 8 introduced removeIf()
for these kind of condition. How can I solve this problem with removeIf()
method ?
但java 8为这些条件引入了removeIf()。如何使用removeIf()方法解决此问题?
1 个解决方案
#1
2
You'll need to it like this :
你需要这样:
map.keySet()
.removeIf(key -> !(key.equals(Constants.search) || key.equals(Constants.context)));
It will iterate over the keys
and remove the ones for those the key
is not one of or two required keys
它将迭代密钥并删除那些密钥不是一个或两个必需密钥的密钥
#1
2
You'll need to it like this :
你需要这样:
map.keySet()
.removeIf(key -> !(key.equals(Constants.search) || key.equals(Constants.context)));
It will iterate over the keys
and remove the ones for those the key
is not one of or two required keys
它将迭代密钥并删除那些密钥不是一个或两个必需密钥的密钥