Method Reference etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Method Reference etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

11 Şubat 2020 Salı

Method Reference Nerede Kullanılır

Giriş
Kural olarak belki şöyle hatırlamak daha kolar.

- Eğer lambda parametre almıyorsa ve sonuç dönmüyorsa
- Eğer lambda tek parametre alıyor ve bir sonuç dönüyorsa

method reference ile yer değiştirebilir.

Ayrıca method reference okunurluğu artırıyor. Açıklaması şöyle


1. Functional Interface Yerine
Bu durumda interface'ten kalıtın yeni bir sınıf yaratmak yerine kendi metodumuzu method reference olarak geçebiliriz. Açıklaması şöyle.
So to use a method reference, you first need a lambda expression with one method. And to use a lambda expression, you first need a functional interface, an interface with just one abstract method.
1.1 Comparator Yerine
Örnek
Double sınıfındaki metodun imzası şöyle.
public int compareTo(Double anotherDouble)
Stream.max() metodu bir Functional interface olan Comparator arayüzünü alır. Dolayısıyla biz de method reference kullanarak şöyle yaparız.
Double maxMethodreference = list.stream()
  .max(Double::compareTo)
  .orElse(Double.NEGATIVE_INFINITY);
1.2. Supplier Parametre Yerine
Supplier bir Functional interface olduğu için Supplier olarak sınıfımızın metodu kullanılabilir.

1.3. Predicate Parametre Yerine
Predicate bir Functional interface olduğu için Predicate olarak sınıfımızın metodu kullanılabilir.

1.4. BiPredicate Parametre Yerine
BiPredicate bir Functional interface olduğu için BiPredicate olarak sınıfımızın metodu kullanılabilir. Metodumuzun iki parametre alması gerekir.



22 Kasım 2018 Perşembe

Method Reference - Reference to Constructor

Giriş
myObject::new şeklinde kullanılır.

Örnek
Elimizde şöyle bir kod olsun.
private static void test(Callable<Object> call) {

}

private static void test(Runnable run) {

}

static class Gen<T> {

}
Generic kod olduğu için Şöyle yaparız. Derleyiciye yardım olma işine type witness deniliyor.
test(Gen<String>::new);
Örnek
Şu kod Reference to Constructor değildir.
UnaryOperator<String>stringToUpperCase = new String()::toUpperCase; 

2 Eylül 2018 Pazar

Method Reference - Object İçin instance metod

Giriş
Açıklaması şöyle. Object::mymethod() şeklinde kullanılır.
The timing of method reference expression evaluation is more complex than that of lambda expressions (§15.27.4). When a method reference expression has an expression (rather than a type) preceding the :: separator, that subexpression is evaluated immediately. The result of evaluation is stored until the method of the corresponding functional interface type is invoked; at that point, the result is used as the target reference for the invocation. This means the expression preceding the :: separator is evaluated only when the program encounters the method reference expression, and is not re-evaluated on subsequent invocations on the functional interface type.
Örnek
Method Refence bir nesne için bir kere alınır. Elimizde şöyle bir kod olsun
public class Instance {

  int member;

  Instance set(int value){
    this.member = value;
    return this;
  }

  @Override
  public String toString() {
    return member + "";
  }

public static void main(String[] args) {

  Stream<Integer> stream1 = Stream.of(1, 2, 3, 4);
  Stream<Integer> stream2 = Stream.of(1, 2, 3, 4);

  List<Instance> collect1 = stream1.map(i -> new Instance().set(i))
    .collect(Collectors.toList());
  List<Instance> collect2 = stream2.map(new Instance()::set)
    .collect(Collectors.toList());

  System.out.println(collect1);
  System.out.println(collect2);
  }
}
Çıktı olarak şunu alırız. Çünkü ikinci kullanımda yeni bir Instance yaratıldıktan sonra hep aynı nesne kullanılıyor.
[1, 2, 3, 4]
[4, 4, 4, 4]
Method Reference'tan Function'a Dönüştürme Genel Kullanım
Örnek
Şöyle yaparız. Instance null olsa bile kod derlenir ve çalışır.
String s = "Hello World";       
Function<Integer, String> f = s::substring;
s = null;
System.out.println(f.apply(5));
Lambda değişkenin final olmasını istediği için şu kod derlenmez.
String s = "Hello World";
Function<Integer, String> f = i -> s.substring(i); // Doesn't compile!
s = null;
System.out.println(f.apply(5));
Örnek
Şöyle yaparız.
NameCreator creator = new NameCreator();
Function<String, String> func = creator::createName;
Method Reference'tan Function'a Dönüştürme - Lambda İçin 
Örnek
Şöyle yaparız
Supplier<Integer> ageSupplier=Person::getAge; // does not compile
Function<Void,Integer> ageFunction=Person::getAge; //also does not compile
Function<Person,Integer> ageFunction=Person::getAge; //compiles correctly. 

people.stream().map(ageFunction)
         .filter(age -> age > 25)
         .forEach(System.out::println);