I just wonder what’s the best way to apply a function that returns Void on an Iterable/Collection?
My usecase is:
- i have a list of
Animalobjects - i want to call on each animal of the list the
eat()function
I have a Function<Animal,Void> which calls input.eat();
It turns out that when i call:
Collections2.transform(animalList,eatFunction);
I dont find this very elegant since i’m not looking for a transformation, but only for an application without any output.
Worst, it does not even work since the Guava transformations are returning views.
What works fine is:
Lists.newArrayList( Collections2.transform(animalList,eatFunction) );
But it’s not elegant.
What is the best way to apply a Void function to an Iterable/Collection, in a functional way with Guava?
Edit:
- Related question: Inverse of Supplier<T> in Guava
- Also as Dzik points out, if you are using Java8 instead of Guava there’s the Consumer class: https://stackoverflow.com/a/32222080/82609
What do you think is more elegant? A plain old for loop:
or a “bending a procedural language by writing a procedural operation in a functional style” madness?
I would vote for the first case.
If you really would like to write your programs in functional style, I would recommend switching to another JVM language.
Scala might be a good alternative for such a case:
or even a shorter variant using the
_placeholder:EDIT:
After trying the code in Eclipse I found out that I had to add the
return nullstatement to theeatFunction, because 1)Voidisn’t the same asvoidand 2) it is uninstantiable. That’s even more ugly then expected! 🙂Also from performance point of view, the invocation of the lazy function by using some copy constructor like above also pointlessly allocates memory. An
ArrayListof the same size as theanimalListfilled only with nulls is created just to be immediately garbage collected.If you really have a use case where you want to pass around some function objects and dynamically apply them on some collections, I would write my own functional interface and a foreach method:
Then you can similarly define a
void(lower case) function:And use it like this: