Bick
Bick

Reputation: 18551

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:

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?

Upvotes: 6

Views: 11729

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100329

As a possible alternative you may use a partitioningBy collector:

Collector<Entry<String, MyObject>, ?, Map<Boolean, Map<String, MyObject>>> collector = 
    Collectors.partitioningBy(e -> e.getKey().contains("["),
                Collectors.toMap(Entry::getKey, Entry::getValue));
Map<Boolean, Map<String, MyObject>> maps = scenarioFieldsMap.entrySet()
        .stream().collect(collector);

This way you don't modify the original map, but create two new maps instead: maps.get(true) is the map which keys contain "[" and maps.get(false) contains all the rest.

Upvotes: 1

Eran
Eran

Reputation: 394146

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.

Upvotes: 11

Related Questions