OO Programming with Java


Advanced Concepts

map is a well-known (higher-order) function on lists that can be defined as follow:

  public static <X,Y> List<Y> map(List<X> xs,Function<X,Y> f) {
	  ArrayList<Y> ys = new ArrayList<Y>();
	  for(X x:xs) ys.add(f.apply(x));
	  return ys;
  }

  public static void main(String[] args) {
    List<Integer> xs = new ArrayList<Integer>();
    xs.add(-1); xs.add(-2); xs.add(-1); xs.add(0); xs.add(1);

    List<Integer> ys = map(xs, x->(x>=0)?x:-x );
    System.out.println(ys);
  }

Exercice: what are the values of xs and ys ? How to define a filter function in Java ?


9 - 17