Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a pre-Java-8 functional interface that's a drop in replacement for java.util.function.Consumer<T>?

In anticipation of moving to Java 8, I'm trying to write my code in a way that's conducive to using lambdas.

I have a need for a functional interface with a single method that takes one argument of some type T and returns void. This is the signature of java.util.function.Consumer's accept() method, but of course I can't use that yet.

Is there another interface in the standard Java 7 (and preferably Java 6) API that I can use instead? I know I can create my own, but esp. until this code is ported to Java 8, it's better for readability if I can use a standard interface that's already familiar from the standard Java 6/7 APIs.

The closest thing I've found so far is com.google.common.base.Function<T,Void>, but (a) it's not part of the standard Java API and (b) its documentation says "instances of Function are generally expected to be referentially transparent -- no side effects", which is contrary to my intended use (with a Void return type).

like image 527
Matt McHenry Avatar asked Mar 03 '14 21:03

Matt McHenry


People also ask

Do we have functional interfaces earlier to Java 8?

We can also call Lambda expressions as the instance of functional interface. Before Java 8, we had to create anonymous inner class objects or implement these interfaces.

How many types of functional interfaces are there in Java 8?

In Java 8, there are 4 main functional interfaces are introduced which could be used in different scenarios.

What is the use of functional interface in Java 8 when to use functional interface in Java 8?

Java 8 provides some built-in functional interfaces and if we want to define any functional interface then we can make use of the @FunctionalInterface annotation. It will allow us to declare only a single method in the interface.


1 Answers

You can create your own interface:

public interface Invokable <T>{
    public void invoke(T param);
}

Alternatively, as suggested, you could use the same interface as the Java 8 Consumer. The source is included in the Java 8 JDK Early Access download, here with all the comments and annotations removed:

public interface Consumer<T>{
    void accept(T t)
    default Consumer<T> andThen(Consumer<? super T> after)
}
like image 50
Charlie Avatar answered Sep 27 '22 18:09

Charlie