简体   繁体   中英

Remove from HashMap if a key is not in the list

Is the any elegant way to remove item from the hash map where the key is not in the given list of items? I would really appreciate if anybody would give a code snippet. If not I would probably do something like this:

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

You can use Set#retainAll :

taskMap.keySet().retainAll(goodList);

From Map#keySet :

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

(emphasis mine)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM