Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional interfaces of java 8 in java 7

Tags:

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.

like image 669
msung Avatar asked Apr 07 '14 07:04

msung


2 Answers

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.

like image 64
assylias Avatar answered Sep 18 '22 21:09

assylias


Here are the signatures of java 8 main functional interfaces as an addition to assylias answer

public interface Consumer<T> {
    void accept(T t);
}

public interface Supplier<T> {
    T get();
}

public interface Function<T, R> {
    R apply(T t);
}

public interface Predicate<T> {
    boolean test(T t);
}
like image 39
mkdev Avatar answered Sep 19 '22 21:09

mkdev