Java Lambda Expression Method References to Instance Methods with different objects

Introduction

To specify an instance method for with any object of a given class, create a method reference as:

ClassName::instanceMethodName 

interface MyFunc<T> {
  boolean func(T v1, T v2);
}

class My {/*from www  . jav a 2 s.c o m*/
  private int myValue;

  My(int ht) {
    myValue = ht;
  }

  boolean equal(My ht2) {
    return myValue == ht2.myValue;
  }

  boolean lessThan(My ht2) {
    return myValue < ht2.myValue;
  }
}

public class Main {
  static <T> int counter(T[] vals, MyFunc<T> f, T v) {
    int count = 0;

    for (int i = 0; i < vals.length; i++)
      if (f.func(vals[i], v))
        count++;

    return count;
  }

  public static void main(String args[]) {
    int count;
    My[] weekDayHighs = { new My(8), new My(2), new My(9), new My(3), 
        new My(4),
        new My(6), new My(-7), new My(-3) };

    count = counter(weekDayHighs, My::equal, new My(0));
    System.out.println(count + " days had a high of 0");

    count = counter(weekDayHighs, My::lessThan, new My(0));
    System.out.println(count + " days had a high less than 0");

  }
}

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    Language[] stusArr = new Language[] { 
        new Language(10, "CSS"), 
        new Language(30, "Java"), 
        new Language(30, "HTML"),
        new Language(20, "Javascript") };
    for (Language stu : stusArr) {
      System.out.println(stu);//from  w w  w . ja  v  a 2s  . com
    }

    System.out.println("##Sort By Age##");
    Arrays.sort(stusArr, (stu1, stu2) -> stu1.age - stu2.age);
    for (Language stu : stusArr) {
      System.out.println(stu);
    }

    System.out.println("##Sort By Name##");
    Arrays.sort(stusArr, new My()::compareByName);
    for (Language stu : stusArr) {
      System.out.println(stu);
    }
  }
}

class Language {
  int age;
  String name;

  public Language(int age, String name) {
    this.age = age;
    this.name = name;
  }

  @Override
  public String toString() {
    return "Language [age=" + age + ", name=" + name + "]";
  }
}

class My {

  public int compareByAge(Language o1, Language o2) {
    return o1.age - o2.age;
  }

  public int compareByName(Language o1, Language o2) {
    return o1.name.compareTo(o2.name);
  }
}

You can refer to the superclass version of a method by use of super:

super::name 



PreviousNext

Related