:: (double colon) operator in Java 8

前端 未结 17 2819
旧时难觅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:45

    I found this source very interesting.

    In fact, it is the Lambda that turns into a Double Colon. The Double Colon is more readable. We follow those steps:

    STEP1:

    // We create a comparator of two persons
    Comparator c = (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
    

    STEP2:

    // We use the interference
    Comparator c = (p1, p2) -> p1.getAge().compareTo(p2.getAge());
    

    STEP3:

    // The magic using method reference
    Comparator c = Comparator.comparing(Person::getAge);
    

提交回复
热议问题