This is a follow up question from :: (double colon) operator in Java 8 in which Java allows you to refer to methods using ::
operator.
Is it possible to provide some custom Functional Interface that I create and use it with ::
operator? And how to do it?
Objects are the base of java programming language and we can never have a function without an Object, that's why Java language provide support for using lambda expressions only with functional interfaces.
A functional interface has only one functionality to exhibit. From Java 8 onwards, we can use lambda expressions to represent the instance of a functional interface. There can be any number of default and static methods in a functional interface that have an implementation.
Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when: passing a comparator to a sort method e.g. List. sort , Stream. sorted , Collections.
“Is it possible to provide some custom Functional Interface that I create and use it with ::
operator? And how to do it?”
It is possible and it’s as easy as you could imagine: just create an interface with exactly one method. You don’t even need the @FunctionalInterface
annotation; this annotation just documents your intention and helps detecting errors at compile time similar to @Override
.
So maybe you already have created such interfaces in your pre-Java 8 projects…
class Foo {
// nothing new:
public interface FooFactory {
Foo createFoo();
}
// new in Java 8:
public static final FooFactory DEFAULT_FACTORY = Foo::new;
}
How to provide custom functional interface implementation to use ::
operator
public class TestingLambda {
public static void main(String[] args) {
int value1 = method(TestingLambda::customMethod1);
int value2 = method(TestingLambda::customMethod2);
System.out.println("Value from customMethod1: " + value1);
System.out.println("Value from customMethod2: " + value2);
}
public static int customMethod1(int arg){
return arg + 1;
}
public static int customMethod2(int arg){
return arg + 2;
}
public static int method(MyCustomInterface ob){
return ob.apply(1);
}
@FunctionalInterface
interface MyCustomInterface{
int apply(int arg);
}
}
I have created my own FunctionalInterface
named MyCustomInterface
and in Java 8 you have to declare the interface to be functional interface using @FunctionalInterface
annotation. Now it has a single method taking int
as param and returning int
.
Created two methods customMethod1
and customMethod2
which confirm to the signature of that custom interface.
MyCustomInterface
) as argumentmethod
takes MyCustomInterface
in the argument.
And you are ready to go.
In the main I have used the method
and passed it the implementation of my custom methods.
method(TestingLambda::customMethod1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With