Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 495
AAaa Avatar asked Jan 19 '23 20:01

AAaa


1 Answers

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.

like image 104
dm3 Avatar answered Jan 30 '23 08:01

dm3