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\",\"
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 result = Collections.transform(input, new Function() {
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 result = Collections.transform(input, SomeClass::frobnicate);
or the more verbose, but more flexible:
Collection result = Collections.transform(input, in -> frobnicate(in));