2014-07-17 34 views
4

是否有任何优雅的方法可以将密钥不在给定列表中的哈希映射中?我真的很感激,如果有人会给一个代码片段。如果不是我可能会做这样的事情:如果密钥不在列表中,则从HashMap中移除

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; 
} 

回答

15

您可以使用Set#retainAll

taskMap.keySet().retainAll(goodList); 

Map#keySet

返回Set查看包含在钥匙这张地图。 该集合由地图支持,因此对地图的更改将反映在集合中,反之亦然。

(重点煤矿)

+2

哇,刚才我问:) – serge

+0

这是否工作'值()的''代替的keySet()'? – Populus