如果一个键不在列表中,从HashMap中删除该键。

12

有没有一种优雅的方式可以从哈希表中删除键不在给定项目列表中的项?如果有人能提供代码片段,我将不胜感激。如果没有,我可能会像这样做:

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;
}
1个回答

32
你可以使用Set#retainAll方法:
taskMap.keySet().retainAll(goodList);

Map#keySet中得知:

返回此映射中所包含的键的 Set 视图。 该集合由映射支持,因此对映射的更改会反映在集合中,反之亦然。

(强调为本人添加)


2
哇,正是我所要求的 :) - serge
这对于values()而不是keySet()有效吗? - Populus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接