radicalmatt radicalmatt - 1 year ago 67
Java Question

How can I write a higher order function like map, or reduce in java?

I read an article on Joel On Software about the idea of using higher order functions to greatly simplify code through the use of map and reduce. He mentioned that this was difficult to do in Java. The article: http://www.joelonsoftware.com/items/2006/08/01.html

The example from the article below, loops through an array, and uses the function fn that was passed as an argument on each element in the array:

function map(fn, a)
for (i = 0; i < a.length; i++)
a[i] = fn(a[i]);

This would be invoked similar to the below in practice:

map( function(x){return x*2;}, a );
map( alert, a );

Ideally I'd like to write a map function to work on arrays, or Collections of any type if possible.

I have been looking around on the Internet, and I am having a difficult time finding resources on the subject. Firstly, are anonymous functions possible in java? Is this possible to do in another way? Will it be available in a future version of java? If possible, how can I do it?

I imagine that if this is not possible in Java there is some kind of 'pattern'/technique that people use to achieve the same effect, as I imagine anonymous functions are a very powerful tool in the software world. the only similar question I was able to find was this: Java generics - implementing higher order functions like map and it makes absolutely no sense to me.

Answer Source

Guava provides map (but it's called transform instead, and is in utility classes like Lists and Collections2). It doesn't provide fold/reduce, however.

In any case, the syntax for using transform feels really clunky compared to using map in Scheme. It's a bit like trying to write with your left hand, if you're right-handed. But, this is Java; what do you expect. :-P

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download