开发者

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

I've read some post comparing Guava and Apache Commons, and 开发者_JAVA技巧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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜