How to perform the function of composition?

While Java 8 is quite eagerly awaiting, and after reading the brilliant article “The State of Lambda” by Brian Goetz , I noticed that the composition of the function was not included at all.

As stated above, in Java 8, the following should be possible:

// having classes Address and Person public class Address { private String country; public String getCountry() { return country; } } public class Person { private Address address; public Address getAddress() { return address; } } // we should be able to reference their methods like Function<Person, Address> personToAddress = Person::getAddress; Function<Address, String> addressToCountry = Address::getCountry; 

Now, if I wanted to put together these two functions to map the Person function to a country, how can I achieve this in Java 8?

+32
java java-8
Nov 07 '13 at 11:20
source share
2 answers

There is a default interface function Function::andThen and Function::compose :

 Function<Person, String> toCountry = personToAddress.andThen(addressToCountry); 
+49
Nov 07 '13 at 13:44
source share

There is one drawback to using compose and andThen . You must have explicit variables, so you cannot use method references, for example:

 (Person::getAddress).andThen(Address::getCountry) 

It will not be compiled. What a pity!

But you can define the utility function and use it happily:

 public static <A, B, C> Function<A, C> compose(Function<A, B> f1, Function<B, C> f2) { return f1.andThen(f2); } compose(Person::getAddress, Address::getCountry) 
+14
Sep 29 '15 at 8:09
source share



All Articles