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 with a map and reduce it. He mentioned that this is difficult to do in Java. Article: http://www.joelonsoftware.com/items/2006/08/01.html

An example from the article below, loop through an array and use the fn function, which was passed as an argument for each element of the array:

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

This will be triggered similarly to the following in practice:

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

Ideally, I would like to write a map function to work with arrays or collections of any type, if possible.

, . -, java? -? Java? , ?

, , Java, - "" /, , , . , , : Java generics - , map, .

+5
5

Guava ( transform , Lists Collections2)), /.

transform map . , . Java; .:-P

+6

, Java. , :

Iterable<Source> foos = ...;
Iterable<Destination> mappedFoos = foos.map(new Function<Source, Destination>() 
{
    public Destination apply(Source item) { return ... }
});

Java . Guava

+3

?

Java?

P.S: try Java. , .

+2
interface Func<V,A> {
    V call (A a);
}

static <V,A> List<V> map (Func<V,A> func, List<A> as) {
    List<V> vs = new ArrayList<V>(as.size());
    for (A a : as) {
        Vs.add(func.call(a));
    }
    return vs;
}
+2

Paguro . , 98% , Java forEach. , , , . ( ) Clojure. Transformable Paguro. java.util, xform().

0

All Articles