functional interfaces of java 8 in java 7

msung picture msung · Apr 7, 2014 · Viewed 16.2k times · Source

are the functional interfaces of java 8 available somewhere (i.e. a jar) so I can use them in a Java 7 project? that way I could later on easier port the code to idiomatic java 8. if not, is that technically possible or do they make use of new features like default methods?

yes, i meant the interfaces in java.util.function. since adding packages with the java prefix seems to be disallowed importing them from somewhere else is not an option.

Answer

assylias picture assylias · Apr 7, 2014

A functional interface is simply an interface with only one non-default, non-static method. All interfaces that satisfy that definition can be implemented through a lambda in Java 8.

For example, Runnable is a functional interface and in Java 8 you can write: Runnable r = () -> doSomething();.

Many of the functional interfaces brought by Java 8 are in the java.util.function package. The most common are:

  • Consumer<T> which has a void accept(T t)
  • Supplier<T> which has a T get()
  • Function<T, R> which has a R apply(T t)
  • Predicate<T> which as a boolean test(T t)

What you could do at this stage is to use single method interfaces wherever it makes sense, if possible with similar signatures. When you migrate to Java 8 you will be able to easily refactor through your IDE from:

someMethod(new MyConsumer<T>() { public void accept(T t) { use(t); } });

into

someMethod(t -> use(t));

Then change the signature of someMethod(MyConsumer<T> mc) into someMethod(Consumer<T> c), get rid of you MyConsumer interface and you are done.