Search code examples
javahashmap

Intersection List between HashMap keys and a given list


Its a simple problem. I have a HashMap of String and Double. This is a toy example.

HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("a", 2.0);
hm.put("b", 4.0);
hm.put("c", 1.0);
hm.put("d", 3.0);

If I have a list tokensList which is for e.g. [b,d]. Can, I get a list which is an intersection of between the elements of list and keys of hashmap.

What I have tried works. But, is there a built in functionality which I'm missing.

List<String> newList = new ArrayList<String>();
for (String word : tokensList) {
    if (hm.containsKey(word.trim())) {
        newList.add(word);
    }
}

Solution

  • You could use List::retainAll.

    List<String> newList  = new ArrayList<>(hm.keySet());
    newList.retainAll(tokensList);