带参数的方法引用

use*_*342 17 java lambda

在Java 8中,使用以下类

 class Person {

    private boolean born;

    Person() {
    }

    public void setBornTrue() {
        born = true;
    }

    public void setBorn(boolean state) {
        born = state;
    }

  }
Run Code Online (Sandbox Code Playgroud)

可以通过方法引用调用setBornTrue方法:

    ArrayList<Person> people = new ArrayList<>();
    people.add(new Person());

    people.forEach(Person::setBornTrue);
Run Code Online (Sandbox Code Playgroud)

但是我如何使用forEach方法并使用方法引用来使用setBorn ?试:

    people.forEach(Person::setBorn);
Run Code Online (Sandbox Code Playgroud)

导致错误,"无法解析方法setBorn".

另外,我如何传递True的值?

Vol*_*une 23

使用lambda:

people.forEach((p) -> p.setBorn(true));
Run Code Online (Sandbox Code Playgroud)

找不到仅使用java 8 API的其他方法.


使用此自定义功能:

public static <T, U> Consumer<T> bind2(BiConsumer<? super T, U> c, U arg2) {
    return (arg1) -> c.accept(arg1, arg2);
}
Run Code Online (Sandbox Code Playgroud)

你可以做:

people.forEach(bind2(Person::setBorn, true));
Run Code Online (Sandbox Code Playgroud)

如果java API或库中提供了这种实用方法,请告诉我们.