Skip to content

Instantly share code, notes, and snippets.

@djcsdy
Created February 10, 2011 18:15
Show Gist options
  • Save djcsdy/821015 to your computer and use it in GitHub Desktop.
Save djcsdy/821015 to your computer and use it in GitHub Desktop.
Example of functional-style ‘map’ in Java. Isn’t it revolting? :)
package net.noiseinstitute.lambda;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Map {
public static <T,U> List<U> map (Collection<T> collection, MapCallback<T,U> callback) {
List<U> list = new ArrayList<U>();
for (T value: collection) {
list.push(callback.mapValue(value));
}
return list;
}
static interface MapCallback<T,U> {
U mapValue (T value);
}
static void main (String args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list = map(list, new MapCallback<Integer,Integer>() {
@Override
public Integer mapValue(Integer value) {
return value * 2;
}
});
// list now contains {2, 4, 6}
System.out.println(list.get(2)); // 6
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment