Java - Generic Functional Interface

Introduction

You can create a generic functional interface.

The Comparator interface with one type parameter T is an example of generic functional interface.

@FunctionalInterface
interface Comparator<T> {
        int compare(T o1, T o2);
}

A functional interface can have a generic abstract method.

The abstract method may declare type parameters.

The following code has a non-generic functional interface called Processor whose abstract method process() is generic:

@FunctionalInterface
interface Processor {
        <T> void process(T[] list);
}

Example

The following code defines a generic functional interface and instantiate it using lambda expressions.

The following Mapper is a generic functional interface with a type parameter T.

map() method takes an object of type T as a parameter and returns an int.

mapToInt() method is a generic static method.

Demo

//use lambda expressions to instantiate the Mapper<T> interface.
//The program maps a String array and an  Integer array to  int arrays.

public class Main {
  public static void main(String[] args) {
    // Map names using their length
    System.out.println("Mapping names to their lengths:");
    String[] names = { "abc", "defg", "this is a test" };
    int[] lengthMapping = Mapper.mapToInt(names, (String name) -> name.length());
    printMapping(names, lengthMapping);//from  w  w  w  .j  a  va2s .c  o  m

    System.out.println("\nMapping integers to their squares:");
    Integer[] numbers = { 7, 3, 67 };
    int[] countMapping = Mapper.mapToInt(numbers, (Integer n) -> n * n);
    printMapping(numbers, countMapping);
  }

  public static void printMapping(Object[] from, int[] to) {
    for (int i = 0; i < from.length; i++) {
      System.out.println(from[i] + " mapped to " + to[i]);
    }
  }
}

interface Mapper<T> {
  // An abstract method
  int map(T source);

  // A generic static method
  public static <U> int[] mapToInt(U[] list, Mapper<? super U> mapper) {
    int[] mappedValues = new int[list.length];

    for (int i = 0; i < list.length; i++) {
      // Map the object to an int
      mappedValues[i] = mapper.map(list[i]);
    }

    return mappedValues;
  }
}

Result