Function composition basically means "pasting functions together to create new functions," and it's commonly considered a part of functional programming.
For example:
// functional/FunctionComposition.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.function.*;
public class FunctionComposition {
static Function<String, String>
f1 =
s -> {
System.out.println(s);
return s.replace('A', '_');
},
f2 = s -> s.substring(3),
f3 = s -> s.toLowerCase(),
f4 = f1.compose(f2).andThen(f3);
public static void main(String[] args) {
System.out.println(f4.apply("GO AFTER ALL AMBULANCES"));
}
}
/* Output:
AFTER ALL AMBULANCES
_fter _ll _mbul_nces
*/
public String substring(int beginIndex)
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Examples:
"unhappy".substring(2) returns "happy"
public static String join(CharSequence delimiter, CharSequence... elements) // this method since 1.8
Returns a new String composed of copies of the CharSequence elements
joined together with a copy of the specified delimiter
.
For example,String message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool"
Note that if an element is null, then "null"
is added.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/functional/FunctionComposition.java
3. https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-