Home > other >  Deleting an item in a List within a HashMap
Deleting an item in a List within a HashMap

Time:03-17

I have a Hashmap<Long, List<Foo>> myMap. I want to remove an item from any List<Foo> where the Foo.key value = the passed in key. Is there a good way to do this with streams? I am using the following code to delete the item, which doesn't seem the best to me:

for (List<Foo> l : myMap.values()) {
   for (Foo f : l) {
      if (f.getKey().equals(key)) {
         l.remove(f);
         break;
      }
   }
}

CodePudding user response:

Probably there are multiple ways to do this. Here is one:

myMap.values().forEach(list->list.removeIf(foo -> Objects.equals(foo.getKey(), key)));

The idea is to go over each list in the map and remove the elements that have the key you want to remove.

CodePudding user response:

The code you have is actually the most suitable tool for this task.

Since you need to modify the contents of the map, it means that you need a stream that will cause side effects. And that is discouraged by the documentation of the Stream API.

But you can enhance your code by using removeIf() method added to the Collection interface with Java-8.

public static void removeFooWithKey(Map<Long, List<Foo>> myMap, 
                               String key) {
    
    for (List<Foo> foos : myMap.values()) {
        foos.removeIf(foo -> foo.getKey().equals(key));
    }
}
  • Related