The simplest way is:
myMap.values().forEach(list -> list.removeIf(foo -> foo.getKey().equals(key)))
But removeIf removes all of the elements of this collection that satisfy the given predicate. It does not equal to your initial code. Probably if your collection consists of unique keys and you need to remove only one object removeIf will do a little overhead and compare all elements of colections.
Solution 1. Remove by first matched index
myMap.values().forEach(list -> IntStream.range(0, list.size()).filter(index -> key.equals(list.get(index).getKey())).findFirst().ifPresent(list::remove))
Solution 2. Own removeFirstIf method
myMap.values().forEach(list -> StreamUtils.removeFirst(list, foo -> key.equals(foo.getKey())));
public class StreamUtils {
private StreamUtils() {
}
public static <T> T removeFirstIf(Iterable<? extends T> collection, Predicate<? super T> condition) {
Objects.requireNonNull(collection);
Objects.requireNonNull(condition);
T value;
final Iterator<? extends T> iterator = collection.iterator();
while (iterator.hasNext()) {
value = iterator.next();
if (condition.test(value)) {
iterator.remove();
return value;
}
}
return null;
}
}
Solution 3. Change your structure to Map<Long, Map<String, Foo>>
Assumption: probably if your List consists of unique keys then you can change your structure from Map<Long, List<Foo>> to Map<Long, Map<String, Foo>>
Removing elements by Key will be simple and fast:
Map<Long, Map<String, Foo>> myMapOfMaps = new HashMap<>();
myMapOfMaps.values().forEach(map -> map.remove(key));