Using the Guava Collections2 Conversion Method to Work with Apache CollectionUtil.forAllDo

I read a post comparing Guava and Apache Commons, and most posters prefer to use Guava.

I also prefer to use Guava, although I often find that I need to combine the capabilities of Guava and Apache Commons.

For example, I want to perform an operation on all elements of a collection.
The only way to do this with Guava is to call the transform method.
But it uses a Function that takes a value and returns another, while I don't need to return another.
For example, I need to add a new entry to Map without changing the collection. With Apache Commons, I would use CollectionUtils.forAllDo .

How can I get the same effect as CollectionUtils.forAlDo without returning some value?

+4
source share
1 answer

I suggest you use a simple foreach for mutations. Guava does not like side effects, and you only confuse readers with non-idiomatic code.

To handle your case, Guava must have an Effect<T> interface with apply(T): void along with the Collections2#foreach(Effect<T>) helper.

+9
source

All Articles