:: (double colon) operator in Java 8

前端 未结 17 2813
旧时难觅i
旧时难觅i 2020-11-21 11:10

I was exploring the Java 8 source and found this particular part of code very surprising:

//defined in IntPipeline.java
@Override
public fin         


        
17条回答
  •  伪装坚强ぢ
    2020-11-21 11:42

    :: Operator was introduced in java 8 for method references. A method reference is the shorthand syntax for a lambda expression that executes just ONE method. Here's the general syntax of a method reference:

    Object :: methodName
    

    We know that we can use lambda expressions instead of using an anonymous class. But sometimes, the lambda expression is really just a call to some method, for example:

    Consumer c = s -> System.out.println(s);
    

    To make the code clearer, you can turn that lambda expression into a method reference:

    Consumer c = System.out::println;
    

提交回复
热议问题