Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 - is there a good way to filter and remove from a map?

I want to filter several objects from a map as follows:

  • Create a new map with the filtered results
  • Remove from original map

Currently I do it using two methods

Map<String, MyObject > map = scenarioFieldsMap.entrySet().stream()
            .filter(e -> e.getKey().contains("["))
            .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()));

scenarioFieldsMap.entrySet().removeIf(e -> e.getKey().contains("["));

Is there a better way to filter and remove?

like image 255
Bick Avatar asked Dec 19 '22 01:12

Bick


1 Answers

The second step can be more efficient if instead of iterating over all the keys (or entries) you only remove the keys present in the other map :

scenarioFieldsMap.keySet().removeAll(map.keySet());

I'm assuming you meant to remove the entries from the original scenarioFieldsMap and not from the new map that you create in the first step.

like image 65
Eran Avatar answered Jan 18 '23 23:01

Eran