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;

资料

官网说明

原文地址:https://www.cnblogs.com/froggengo/p/14665399.html