java8中的部分函数应用

java8中的部分函数应用,java,functional-programming,java-8,Java,Functional Programming,Java 8,我想使用Java8新引入的函数对象对一些参数部分应用一个遗留方法 以下是所讨论的方法: /** * Appends a {@code character} a couple of {@code times} to a {@code string}. * * @return the string with the appended characters as a StringBuilder */ private static StringBuilder appendChar(char ch

我想使用Java8新引入的函数对象对一些参数部分应用一个遗留方法

以下是所讨论的方法:

/**
 * Appends a {@code character} a couple of {@code times} to a {@code string}.
 *
 * @return the string with the appended characters as a StringBuilder
 */
private static StringBuilder appendChar(char character, int times, String string) {
    StringBuilder strBuilder = new StringBuilder(string);
    for (int i = 0; i < times; i++) {
        strBuilder.append(character);
    }
    return strBuilder;
}
/**
*将{@code character}附加到{@code string}上几次{@code times}。
*
*@作为StringBuilder返回带有附加字符的字符串
*/
私有静态StringBuilder appendChar(字符、整数倍、字符串){
StringBuilder strBuilder=新的StringBuilder(字符串);
for(int i=0;i
这实现了我想要做的事情:

/*
 * Pass two arguments. The created function accepts a String and
 * returns a StringBuilder
 */
Function<String, StringBuilder> addEllipsis = appendToMe -> appendChar(
        '.', 3, appendToMe);
/*
 * Pass one argument. This creates a function that takes another two
 * arguments and returns a StringBuilder
 */
BiFunction<String, Integer, StringBuilder> addBangs = (appendToMe,
        times) -> appendChar('!', times, appendToMe);

// Create a function by passing one argument to another function
Function<String, StringBuilder> addOneBang = appendToMe -> addBangs
        .apply(appendToMe, 1);

StringBuilder res1 = addBangs.apply("Java has gone functional", 2);
StringBuilder res2 = addOneBang.apply("Lambdas are sweet");
StringBuilder res3 = addEllipsis.apply("To be continued");
以下是如何使用自定义函数对象:

/*
* Pass one of the arguments. This creates a function accepting three
* arguments.
*/
TriFunction<Integer, Double, Float, Boolean> partiallyApplied = (i, d, f) ->
                                                           manyArgs("", i, d, f);

/*
* Provide the rest of the arguments.
*/
boolean res4 = partiallyApplied.apply(2, 3.0, 4.0F);
System.out.println("No time for ceremonies: " + res4);
/*
*传递其中一个参数。这将创建一个接受三个参数的函数
*争论。
*/
三函数部分应用=(i,d,f)->
manyArgs(“,i,d,f);
/*
*提供其余的参数。
*/
布尔res4=部分应用。应用(2,3.0,4.0F);
System.out.println(“没有时间举行仪式:+res4”);

不可避免地使用了
apply
不幸地提醒我们,函数在Java中并不是一流的…@ach无论如何,它们是对象,对象在Java中是一流的。
private static boolean manyArgs(String str, int i, double d, float f) {
    return true;
}
/*
* Pass one of the arguments. This creates a function accepting three
* arguments.
*/
TriFunction<Integer, Double, Float, Boolean> partiallyApplied = (i, d, f) ->
                                                           manyArgs("", i, d, f);

/*
* Provide the rest of the arguments.
*/
boolean res4 = partiallyApplied.apply(2, 3.0, 4.0F);
System.out.println("No time for ceremonies: " + res4);