根据键的子集过滤映射的元素,而无需迭代整个事物
我有一个 Map
和一个 Set
。有没有办法将映射的键与字符串集“相交”,以便仅保留具有给定键的对,而不迭代整个映射?我主要关心的是性能和重新发明轮子,让事情可以更优雅地完成。
I have a Map<String, ArrayList>
and a Set<String>
. Is there a way to "intersect" the keys of the map with the set of strings such that only the pairs with the given key remain, without iterating over the entire map? My main concern is performance and re-inventing the wheel on something that can be done more elegantly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就这样做:
按照 javadoc,键集中的更改会反映在地图中。
这是一个演示:
Just do:
As per the javadoc, the changes in the key set are reflected back in the map.
Here's a demo:
详细阐述 BalusC 的出色答案,values() 也支持 keepAll():
retailAll 也保留重复值,正如您所期望的:
Elaborating on BalusC's excellent answer, values() supports retainAll() as well:
retailAll retains duplicate values as well, as you would expect: