Using the functional interface in Java 8

This is the next question from the :: (double colon) operator in Java 8 , in which Java allows you to reference methods using the :: operator.

Is it possible to create some kind of user functional interface that I create and use it with the :: operator? But how to do it?

+6
source share
3 answers

"Is it possible to create some user functional interface that I create and use it with the :: operator? And how to do it?"

It is possible and as easy as you might imagine: just create an interface with one method. You don't even need the @FunctionalInterface annotation; this annotation simply documents your intent and helps detect compile-time errors similar to @Override .

So, perhaps you have already created such interfaces in your projects before Java 8 ...

 class Foo { // nothing new: public interface FooFactory { Foo createFoo(); } // new in Java 8: public static final FooFactory DEFAULT_FACTORY = Foo::new; } 
+11
source

How to ensure the implementation of the user functional interface for using the 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); } } 

Stage 1. Creation of the user functional interface

I created my own FunctionalInterface called MyCustomInterface , and in Java 8 you have to declare the interface as a functional interface using the @FunctionalInterface annotation. Now it has a single method that accepts int as param and returns int .

Step 2. Create some methods to confirm this signature.

Two methods are customMethod1 and customMethod2 , which confirm the signature of this user interface.

Step 3. Create a method that uses the functional interface ( MyCustomInterface ) as an argument

method takes an argument to MyCustomInterface .

And you are ready to go.

Stage 4: use

I mainly used method and passed it an implementation of my own methods.

 method(TestingLambda::customMethod1); 
+3
source

Here you go

 import java.util.Arrays; class Sort { public int compareByLength(String s1, String s2) { return (s1.length() - s2.length()); } } public class LambdaReferenceExample1 { public static void main(String[] javalatteLambda) { String[] str = {"one", "two", "3", "four", "five", "sixsix", "sevennnnn", "eight"}; Sort sort = new Sort(); Arrays.sort(str, sort::compareByLength); for (String s : str) { System.out.println(s); } } } 
+1
source

Source: https://habr.com/ru/post/958305/


All Articles