AAaa
AAaa

Reputation: 3829

Using Guava Collections2 transform method to work as Apache CollectionUtil.forAllDo

I've read some post comparing Guava and Apache Commons, and most of the posters prefer using Guava.

I also prefer using Guava, though I frequently find myself the need to combine Guava and Apache Commons abilities.

For example, I want to perform an operation on all elements of a collection.
The only way I can do it using Guava is by calling the transform method.
But it uses Function which gets a value and returns another one, while I don't need to return another one.
I only need, for example, to put some new entry to a Map, without changing the collection. With Apache Commons I would use CollectionUtils.forAllDo.

How can I get the same effect as CollectionUtils.forAlDo without having to return some value?

Upvotes: 4

Views: 980

Answers (1)

dm3
dm3

Reputation: 2058

I'd suggest you use a simple foreach loop for mutations. Guava doesn't like side-effects and you would only confuse readers with un-idiomatic code.

In order to handle your case, Guava should have had an Effect<T> interface with apply(T): void method along with a Collections2#foreach(Effect<T>) helper.

Upvotes: 9

Related Questions