java 8 - Return method reference -


i playing around in java 8. how can return method reference?

i able return lambda not method reference.

my attempts:

public supplier<?> foreachchild(){      return new arraylist<?>::foreach; } 

or

public function<?> foreachchild(){      return new arraylist<?>::foreach; } 

you have small mis-understanding of how method-references work.

first of all, cannot new method-reference.

then, let's reason through want do. want method foreachchild able return accept list , consumer. list on object invoke foreach on, , consumer action perform on each element of list. that, can use biconsumer: represents operation taking 2 parameters , returning no results: first parameter list , second parameter consumer.

as such, following work:

public <t> biconsumer<list<t>, consumer<? super t>> foreachchild() {     return list::foreach; } 

this type of method-reference called "reference instance method of arbitrary object of particular type". happens first parameter of type list<t> becomes object on foreach invoked, giving parameter consumer.

then can use like:

foreachchild().accept(arrays.aslist("1", "2"), system.out::println); 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -