Java Double Colon Operator

Java :: 연산자 (Double Colon Operator)는 람다식을 대체하여 메서드 참조(method reference)로 사용된다. 즉, 람다식이 사용될 수 있는 Functional Interface Implementation에서만 사용 가능하다.

    • Using Lambda
      Comparator<Person> c = (Person p1, Person p2) ->
                          p1.getName().compareTo(p2.getName());  
      
    • Using Lambda with type interference
      Comparator<Person> c = (p1, p2) -> p1.getName().CompareTo(p2.getName());
    • Using method reference ( :: operator)
      Comparator<Person> c = Comparator.comparing(Person::getName);
    • Method reference  ( :: operator)
      Function<Person, String> getName = Person::getName; // Person->String
      String name = getName.apply(person1); 
      
    • Method reference ( :: operator)는 람다식과 동일한 처리를 하는 식이지만 메소드 본문을 제공하는 대신 기존 메소드를 이름으로 참조한다.
      Function<Double, Double> sq = (Double x) -> x * x; // lambda 
      double result = sq.apply(3); // 3 * 3 = 9
       
      Function<Double, Double> sq2 = MyClass::square; // MyClass에 정의된 square 정적 메소드
      double result2 = sq2.apply(3); // 3 * 3 = 9
      BiFunction<Double, Double, Double> add = (x, y) -> x + y; // lambda
      double result = add.apply(3.1, 3.2); // 3.1 + 3.2 = 6.3
      
      BiFunction<Double, Double, Double> add2 = MyClass::sum; // MyClass에 정의된 sum 정적 메소드 
      double result2 = add2.apply(3.1, 3.2); // 3.1 + 3.2 = 6.3