OO Programming with Java


Advanced Concepts

map and filter are particular use of reduce function, and this one can serve to build most of the functions on lists:

  public static <X,Y> Y reduce(List<X> xs,Y v,BiFunction<Y,X,Y> f) {
	  Y r = v;
	  for(X x:xs) r = f.apply(r, x);
	  return r;
  }
  
  public static void main(String[] args) {
    List<Integer> xs = Arrays.asList(-1,-2,-1,0,1);
    int sum = reduce(xs, 0,(x,y)->x+y);
    int max = reduce(xs,-9,(x,y)->(x<y)?x:y);
    System.out.printf("sum: %d, max: %d",sum,max);
  }

13 - 17