[英]Remove from HashMap if a key is not in the list
是否有任何优雅的方法从哈希映射中删除项目,其中键不在给定的项目列表中? 如果有人提供代码片段,我将非常感激。 如果不是,我可能会做这样的事情:
public HashMap<Integer, NameAndID> getTasksWithWordInFormula(Session session,
HashMap<Integer, NameAndID> taskMap, int sectionID, int topicID, int wordID) {
@SuppressWarnings("unchecked")
List<Integer> goodList = session.createCriteria(Frbw.class)
.add(Restrictions.in("id.formulaId", taskMap.keySet()))
.add(Restrictions.eq("sectionId", sectionID))
.add(Restrictions.eq("topicId", topicID))
.add(Restrictions.eq("wordId", wordID))
.setProjection(Projections.projectionList()
.add(Projections.property("id.formulaId")))
.setCacheable(true).setCacheRegion("query.DBParadox").list();
ArrayList<Integer> toRemove = new ArrayList<Integer>();
for (Integer formulaID : taskMap.keySet())
if (!goodList.contains(formulaID))
toRemove.add(formulaID);
for (Integer formulaID : toRemove)
taskMap.remove(formulaID);
return taskMap;
}
您可以使用Set#retainAll
:
taskMap.keySet().retainAll(goodList);
来自Map#keySet
:
返回此映射中包含的键的
Set
视图。 该集由地图支持,因此对地图的更改将反映在集中,反之亦然。
(强调我的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.