如果某个键不在列表中,则从HashMap中删除

ser*_*rge 8 java 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;
}
Run Code Online (Sandbox Code Playgroud)

ars*_*jii 21

你可以使用Set#retainAll:

taskMap.keySet().retainAll(goodList);
Run Code Online (Sandbox Code Playgroud)

来自Map#keySet:

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

(强调我的)

  • 哇,就是我要求的:) (2认同)