Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove from HashMap if a key is not in the list

Tags:

java

hashmap

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;
}
like image 853
serge Avatar asked Jul 17 '14 16:07

serge


Video Answer


1 Answers

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)

like image 64
arshajii Avatar answered Oct 16 '22 12:10

arshajii