[英]Use of Functional Interface in Java 8
“是否有可能提供我創建的一些自定義功能接口並將其與::
運算符一起使用? 怎么做?“
這是可能的,它就像你想象的那樣簡單:只需用一種方法創建一個界面。 你甚至不需要@FunctionalInterface
注釋; 這個注釋只記錄了你的意圖,並有助於在編譯時檢測錯誤,類似於@Override
。
所以也許你已經在Java 8之前的項目中創建了這樣的接口......
class Foo {
// nothing new:
public interface FooFactory {
Foo createFoo();
}
// new in Java 8:
public static final FooFactory DEFAULT_FACTORY = Foo::new;
}
如何使用::
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);
}
}
我創建了自己的名為MyCustomInterface
的FunctionalInterface
,在Java 8中,您必須使用@FunctionalInterface
注釋將接口聲明為功能接口。 現在它有一個方法,將int
作為param並返回int
。
創建了兩個方法customMethod1
和customMethod2
,它們確認該自定義接口的簽名。
MyCustomInterface
)作為參數的方法 method
在參數中使用MyCustomInterface
。
你准備好了。
在主要方面,我使用了該method
並將其傳遞給我自定義方法的實現。
method(TestingLambda::customMethod1);
干得好
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.