how can you emulate functional programming in java, specifically, doing things like map a function to a collection of items?
map(func, new String[]{\"a\",\"
I have used lambdaj and functionaljava for this sort of things. And there are probably others...
As you note, Java isn't designed for functional programming and while you can emulate it, you have to really want to do this even if is it more verbose and more awkward than using standard programming in Java.
Take @Joachim's example.
Collection<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
public OutputType apply(InputType input) {
return frobnicate(input);
}
});
This uses 12 symbols, not counting close brackets. The same thing in plain Java would look like.
List<OutputType> list = new ArrayList();
for(InputType in: input)
list.add(frobnicate(in));
This uses 7 symbols.
You can do functional programming in Java, but you should expect it to be more verbose and awkward than using the natural programming style of Java.
You could download OpenJDK 8 which is scheduled for prodcution release next year and use the new Lambda Expressions for functional programming. See http://macgyverdev.blogspot.se/2012/10/functional-programming-in-java.html for examples of how these closures will be used in the Collection APIs and how they compare with pre-Java 8 solutions like Guava and LambdaJ.
All attempts of functional programming will have some part of verbose and/or awkward to it in Java, until Java 8.
The most direct way is to provide a Function
interface (such as this one form Guava) and provide all kinds of methods that take and call it (such as Collections#transfrom() which does what I think your map()
method should do).
The bad thing about is that you need to implement Function
and often do so with an anonymous inner class, which has a terribly verbose syntax:
Collection<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
public OutputType apply(InputType input) {
return frobnicate(input);
}
});
Lambda expressions (introduced in Java 8) make this considerably easier (and possibly faster). The equivalent code using lambdas looks like this:
Collection<OutputType> result = Collections.transform(input, SomeClass::frobnicate);
or the more verbose, but more flexible:
Collection<OutputType> result = Collections.transform(input, in -> frobnicate(in));
Just wrap the function you want to apply on the list with a class or an interface.
public interface Func {
Object f(Object input);
}
public void map (Func func, Object[] arr) {
for(int i=0;i<arr.legnth;i++) {
arr[i] = func.f(arr[i]);
}
}
map(
new Func() { public Object f(Object input) { return input; } };,
new String[]{"a","b"});