lamdba式は簡略化できます
以下では、メソッドまたはコンストラクター参照とも呼ばれるlamdbaを単純化する6つの方法を紹介します。
ラムダ式がこのメソッドを直接呼び出すことを表す場合は、呼び出し方法を説明するのではなく、名前で呼び出す方が適切です。メソッドの名前を明示的に指定すると、コードが読みやすくなります。
1.パラメータカテゴリとリターンタイプは、機能インターフェイスの抽象メソッドと一致している必要があります
。2 。パラメータリストの最初のパラメータがインスタンスメソッドの呼び出し元であり、2番目のパラメータがインスタンスメソッドのパラメータである場合、ClassNameを使用できます。 :方法
Object :: instanceメソッド-メソッドリファレンス
//用lambda表达式实现
Consumer consumer = x -> System.out.println(x);
consumer.accept("hello world");
//out实现了println方法
Consumer consumer1 =System.out::println;
consumer1.accept("hello word 1");
クラス名::静的メソッド-メソッドリファレンス
//用lambda表达式实现
BiFunction<Integer, Integer, Integer> biFun = (x,y) -> Integer.compare(x,y);
//类名::静态方法
BiFunction<Integer, Integer, Integer> biFun1 = Integer::compare;
int result1 = biFun.apply(100,200);
int result2 = biFun1.apply(100,200);
クラス名::インスタンスメソッド-メソッドリファレンス
//用lambda表达式实现
BiFunction<String,String,Boolean> fun1 = (s1,s2)-> s1.equals(s2);
//类名::实例方法
BiFunction<String,String,Boolean> fun2 = String::equals;
fun1.apply("hello","hello");
fun2.apply("hello","hello");
クラス名:: new-コンストラクターリファレンス
//用lambda表达式实现
Supplier<String> sup = ()->new String();
//构造方法引用 类名::new
Supplier<String> sup1 = String::new;
クラス名:: new()-コンストラクターリファレンス
//用lambda表达式实现
Function<String,Integer> function = x->new Integer(x);
//类名::new
Function<String,Integer> function1 = Integer::new;
function1.apply("100");
String [] ::: new--配列参照
//用lambda表达式实现
Function <Integer,String[]> array = x -> new String [x];
//类型[]::new
Function <Integer,String[]> array1 = String[]::new;
array1.apply(5);
すべてのコード実行結果:
エラーなし
1000
10
Process finished with exit code 0