java基礎-匿名函數


匿名函數

::操作符

  • A static method (ClassName::methName)
  • An instance method of a particular object (instanceRef::methName)
  • A super method of a particular object (super::methName)
  • An instance method of an arbitrary object of a particular type (ClassName::methName)
  • A class constructor reference (ClassName::new)
  • An array constructor reference (TypeName[]::new)
  1. 靜態方法引用,如System.out::println
  2. 對象方法引用,如Person::getAge
  3. 構造方法引用,如ArrayList::new
  4. 數組構造器的引用,如String[]::new
  5. 超類方法的引用,如super::method

BiConsumer

@Test
public void testBiConsumer (){
    BiConsumer<Person, String> biConsumerRef = Person::setName;
    BiConsumer<Person, String> biConsumer = (Person person, String name) -> person.setName(name);
    test(Person::setAge);
    test((Person a ,Integer b)->a.setAge(b));
}
public static  void  test(BiConsumer<Person,Integer> consumer){
    Person person = new Person("1", 28);
    consumer.accept(person,2);
    System.out.println(person);
}

Consumer

@Test
public void testObjectMethod() {
    List<String> list = Arrays.asList("aaaa", "bbbb", "cccc");
    //對象實例語法	instanceRef::methodName
    list.forEach(this::print);
    list.forEach(n-> System.out.println(n));
}

public void print(String content){
    System.out.println(content);
}

數組構造器

@Test
public void testArray (){
    IntFunction<int[]> arrayMaker = int[]::new;
    // creates an int[10]
    int[] array = arrayMaker.apply(10);
    array[9]=10;
    System.out.println(array[9]);
}

構造方法

public class Example {

    private String name;

    Example(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        InterfaceExample com = Example::new;
        Example bean = com.create("hello world");
        System.out.println(bean.name);
    }

    interface InterfaceExample {

        Example create(String name);
    }
}

這里的用法可能覺得很奇怪。理解一點函數式接口與方法入參以及返回類型一樣,就能將該方法賦值給該接口

這里的Example::newExample create(String name)的入參以及返回值都一樣,所以可以直接賦值

InterfaceExample com = Example::new;

資料

官網說明


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM