# Thinking Functional Programming with Map and Fold in your Everyday Java

· Java Zone · Interview
Save
21.01K Views

in functional programming, map and fold are two extremely useful operators, and they belong to every functional language. if the map and fold operators are so powerful and essential, how do you explain that we can do our job using java even though the java programming language is lacking these two operators? the truth is that you already do map and fold when you code in java, except that you do them by hand each time, using loops.

### you’re already familiar with it

imagine a list<double> of vat-excluded amounts. we want to convert this list into another corresponding list of vat-included amounts. first we define a method to add the vat to one single amount:

```public double addvat(double amount, double rate) {return amount * (1 + rate);}

```

now let’s apply this method to each amount in the list:

```public list<double> addvat(list<double> amounts, double rate){
final list<double> amountswithvat = new arraylist<double>();
for(double amount : amounts){
}
return amountswithvat;
}

```

here we create another output list, and for each element of the input list, we apply the method addvat() to it and then store the result into the output list, which has the exact same size. congratulations, as we have just done, by hand, a map on the input list of the method addvat(). let’s do it a second time.

now we want to convert each amount into another currency using the currency rate, so we need a new method for that:

```public double convertcurrency(double amount, double currencyrate){return amount / currencyrate;}

```

now we can apply this method to each element in the list:

```public list<double> convertcurrency(list<double> amounts, double currencyrate){
final list<double> amountsincurrency = new arraylist<double>();
for(double amount : amounts){
}
return amountsincurrency;
}

```

notice how the two methods that accept a list are similar, except the method being called at step 2:

1. create an output list,
2. call the given method for each element from the input list and store the result into the output list
3. return the output list.

you do that often in java, and that’s exactly what the map operator is: apply a given method somemethod(t):t to each element of a list<t>, which gives you another list<t> of the same size.

functional languages recognize that this particular need (apply a method on each element of a collection) is very common so they encapsulate it directly into the built-in map operator. this way, given the addvat(double, double) method, we could directly write something like this using the map operator:

`list amountswithvat = map (addvat, amounts, rate)`

yes the first parameter is a function, as functions are first-class citizens in functional languages so they can be passed as parameter. using the map operator is more concise and less error-prone than the for-loop, and the intent is also much more explicit, but we don’t have it in java…

so the point of these examples is that you are already familiar, without even knowing, with a key concept of functional programming: the map operator.

### and now for the fold operator

coming back to the list of amounts, now we need to compute the total amount as the sum of each amount. super-easy, let’s do that with a loop:

```public double totalamount(list<double> amounts){
double sum = 0;
for(double amount : amounts){
sum += amount;
}
return sum;
}```

basically we’ve just done a fold over the list, using the function ‘+=’ to fold each element into one element, here a number, incrementally, one at a time. this is similar to the map operator, except that the result is not a list but a single element, a scalar.

this is again the kind of code you commonly write in java, and now you have a name for it in functional languages: « fold » or « reduce ». the fold operator is usually recursive in functional languages, and we won’t describe it here. however we can achieve the same intent in an iterative form, using some mutable state to accumulate the result between iterations. in this approach, the fold takes a method with internal mutable state that expects one element, e.g. somemethod(t), and applies it repeatedly to each element from the input list<t>, until we end up with one single element t, the result of the fold operation.

typical functions used with fold are summation, logical and and or, list.add() or list.addall(), stringbuilder.append(), max or min etc.. the mindset with fold is similar to aggregate functions in sql.

### thinking in shapes

thinking visually (with sloppy pictures), map takes a list of size n and returns another list of the same size:

on the other hand, fold takes a list of size n and returns a single element (scalar):

you may remember my previous articles on predicates , which are often used to filter collections into collections with less elements. in fact this filter operator is the third standard operator that complements map and fold in most functional languages.

### eclipse template

since map and fold are quite common it makes sense to create eclipse templates for them, e.g. for map:

### getting closer to map and fold in java

map and fold are constructs that expect a function as a parameter, and in java the only way to pass a method is to wrap it into a interface.

in apache commons collections, two interfaces are particularly interesting for our needs: transformer , with one method transform(t):t , and closure , with one single method execute(t):void . the class collectionutils offers the method collect(iterator, transformer) which is basically a poor-man map operator for java collections, and the method foralldo() that can emulate the fold operator using closures.

with google guava the class iterables offers the static method transform(iterable, function) which is basically the map operator.

```list<double> exvat = arrays.aslist(new double[] { 99., 127., 35. });
iterable<double> incvat = iterables.transform(exvat, new function<double, double>() {
public double apply(double exvat) {
return exvat * (1.196);
}
});
system.out.println(incvat); //print [118.404, 151.892, 41.86]```

a similar transform() method is also available on the classes lists for lists and maps for maps.

to emulate the fold operator in java, you can use a closure interface, e.g. the closure interface in apache commons collection, with one single method with only one parameter, so you must keep the current -mutable- state internally, just like ‘+=’ does.

unfortunately there is no fold in guava, though it is regularly asked for , and there even no closure-like function, but it is not hard to create your own,  for example, you can implement the grand total above with something like this:

```// the closure interface with same input/output type
public interface closure<t> {
t execute(t value);
}

// an example of a concrete closure
public class summingclosure implements closure<double> {
private double sum = 0;

public double execute(double amount) {
sum += amount; // apply '+=' operator
return sum; // return current accumulated value
}
}

// the poor man fold operator
public final static <t> t foreach(iterable<t> list, closure<t> closure) {
t result = null;
for (t t : list) {
result = closure.execute(t);
}
return result;
}

@test // example of use
public void testfold() throws exception {
summingclosure closure = new summingclosure();

list<double> exvat = arrays.aslist(new double[] { 99., 127., 35. });
double result = foreach(exvat, closure);
system.out.println(result); // print 261.0
}```

### not only for collections: fold over trees and other structures

the power of map and fold is not limited to simple collections, but can scale to any navigable structure, in particular trees and graphs.

imagine a tree using a class node with its children. it may be a good idea to code once the depth-first and the breadth-first searches (dfs & bfs) into two generic methods that accept a closure as single parameter:

```public class node ...{
...
public void dfs(closure closure){...}
public void bfs(closure closure){...}
}```

i have regularly used this technique in the past, and i can tell it can cut the size of your classes big time, with only one generic method instead of many similar-looking methods that would each redo their own tree traversal. more importantly, the traversal can be unit-tested on its own using a mock closure. each closure can also be unit-tested independently, and all that just makes your life so much simpler.

a very similar idea can be realized with the visitor pattern, and you are probably already familiar with it. i have seen many times in my code and in the code of several other teams that visitors are well-suited to accumulate state during the traversal of the data structure. in this case the visitor is just a special case of closure to be passed for use in the folding.

### one word on map-reduce

you probably heard of the pattern map-reduce , and yes the words « map » and « reduce » in it refer to the same functional operators map and fold (aka reduce) we’ve just seen. even though the practical application is more sophisticated, it is easy to notice that map is embarrassingly parallel , which helps a lot for parallel computations.

Topics:

Opinions expressed by DZone contributors are their own.