Reputation: 55
I have a hashmap consisting of keys as words ( strings) and values as their counts ( integer).
I have to remove stopwords from the hashmap. Essentially , I have to do a hMap.remove("then") , hMpa.remove("where") for some 67 words. Is there any easier way of doing it ? Can I delete multiple keys from a hashmap in a single stroke.
Upvotes: 0
Views: 891
Reputation: 4713
The following should help you out;
Map<String, Integer> ohm = new HashMap<String, Integer>();
List<String> al = new ArrayList<String>();
al.add("One");
al.add("Two");
ohm.put("One", 1);
ohm.put("Two", 2);
ohm.put("Three", 3);
ohm.keySet().removeAll(al);
System.out.println(ohm); // Output: [Three = 3]
Hope this helps.
Upvotes: 1
Reputation: 2085
@user2623946 No, you must use a collection for it. Or something like that:
String[] arr = {"a","b","c"};
myMap.keySet().removeAll(Arrays.asList(arr));
Upvotes: 2
Reputation: 6618
Use hMap.keySet().removeAll(the_stuff_you_want_to_remove)
From the documentation:
The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.
Upvotes: 5