Bringing Higher Order Functions to Java

Sometimes you want to be able to use higher order functions in Java. This is useful if for example you want to be able to map different functions over a list. We can work around Java's lack of high order functions by imitating them with objects. Below is an example implementation of map using objects to pass functions.

public class Functional {

    public int[] map(int[] list, Func func){ t
        for(int i = 0; i < list.length; i++) {
            list[i] = func.apply(i);
        }
    }

}

We'll start with a base class called Func for our functions to inherit from.

class Func {

    public int apply(int x,int y) {
        return -1;
    }
}

This way if we want to pass a function to map we can create a subclass of Func.

class AddOne extends Func {
    public int apply(int x) {
        return x+1;
    }
}

We can now pass arbitrary one parameter functions to map.

import java.util.Arrays;

public class Functional {

      class Func {

          public int apply(int x) {
              return -1;
          }

      }

      public int[] map(int[] list, Func func){
          int[] ret = new int[list.length];
          for(int i = 0; i < list.length; i++){
                ret[i] = func.apply(list[i]);
            }
          return ret;
        }

      public class Sub1 extends Func {
          public int apply(int x) {
              return x-1;
          }
      }

      class Add5 extends Func {
          public int apply(int x) {
              return x+5;
          }
      }

    public void runMap() {
        int[] arr = new int[]{0,1,2,3,4,5};
        System.out.println(Arrays.toString(arr));
        Sub1 sub = new Sub1();
        System.out.println(Arrays.toString(map(arr,sub)));
        Add5 add = new Add5();
        System.out.println(Arrays.toString(map(arr,add)));
    }

      public static void main(String[] args) {
          Functional f = new Functional();
          f.runMap();

      }
  } 

Output demonstrating function mapping.

alice$ java Functional
[0, 1, 2, 3, 4, 5]
[-1, 0, 1, 2, 3, 4]
[5, 6, 7, 8, 9, 10]

Last updated: 2019-11-28 Thu

Home