create a list of method references with different

2019-09-14 20:40发布

问题:

I am still digesting the lambda conception in Java 8. Now it comes to a need of create a list of method references in my service, which has 2 other services objects. This is what needs to happen

Person person = new Person();
this.method1(person);
service2.method2(person);
service3.method3(person);

so the list should have

0 -> this.method1,
1 -> service2.method2,
2 -> service3.method3,

It is very important that no new instances of this.class, service2 or service3 is created. Not sure the best way to achieve that. Can I have some help?

回答1:

It looks like you just want a

List<Consumer<Person>> list = Arrays.asList(
    this::method1, service2::method2, service3::method3);
for (Consumer<Person> action : list) {
  action.accept(person);
}