Sagar
Sagar

Reputation: 5596

Streaming the map and modifying it in Java 8

I know that once we create the stream off of a collection we should not modify collection while consuming the stream, However not sure if following approach works where I am modifying the entry inside the map and not adding or removing anything from it. Also, is this the right way to stream the map always and consume it ?

creepyCategoryStatuses.entrySet().stream().forEach(entry -> {
        String creepyBlockResponse = (String) getBlockResponse(entry.getKey());
        if (creepyBlockResponse.equalsIgnoreCase("block")){
            entry.setValue(true); 
         //OR creepyCategoryStatuses(entry.getKey(), true);
        }
    });

Upvotes: 1

Views: 87

Answers (3)

Holger
Holger

Reputation: 298599

This kind of modification is no problem as setting the value of an entry is not a structural modification. However, it’s worth noting that there are more Java 8 features than the Stream API or the forEach method:

creepyCategoryStatuses.replaceAll((key,value)->
    ((String)getBlockResponse(key)).equalsIgnoreCase("block")||value
);

does the job much easier. Note that ||value will retain the old value if the condition evaluates to false as in your original code.

Upvotes: 4

Alexis C.
Alexis C.

Reputation: 93902

According to your use-case, you could use replaceAll here:

creepyCategoryStatuses.replaceAll((k, v) -> ((String) getBlockResponse(k)).equalsIgnoreCase("block") ? true : v);

I always favor functional paradigms, so I would collect the new data into a new map, but that's a matter of taste.

Upvotes: 2

Tagir Valeev
Tagir Valeev

Reputation: 100349

Yes, such usage of Map seems to be legit. Note that in this case you don't need the stream. You can simply use

creepyCategoryStatuses.entrySet().forEach(entry -> {...});

Upvotes: 2

Related Questions