[英]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.