Java8方法引用用作Function对象来组合函数

Java8方法引用用作Function对象来组合函数

问题描述:

Java8中是否有办法使用方法引用作为 Function 对象来使用其方法,如:

Is there a way in Java8 to use a method reference as a Function object to use its methods, something like:

Stream.of("ciao", "hola", "hello")
    .map(String::length.andThen(n -> n * 2))

此问题与 Stream $ c $无关c>,它只是用作例子,我想对方法参考有答案

This question is not related to the Stream, it is used just as example, I would like to have answer about the method reference

你可以写一个静态的执行此操作的方法:

You can write a static method to do this:

import java.util.function.*;

class Test {
    public static void main(String[] args) {
        Function<String, Integer> function = combine(String::length, n -> n * 2);
        System.out.println(function.apply("foo"));
    }

    public static <T1, T2, T3> Function<T1, T3> combine(
        Function<T1, T2> first,
        Function<T2, T3> second) {
        return first.andThen(second);
    }
}

然后你可以将它放在一个实用程序类中并导入静态地。

You could then put it in a utility class and import it statically.

或者,创建一个更简单的静态方法,只是返回它给出的函数,为了让编译器知道你的'重做:

Alternatively, create a simpler static method which just returns the function it's given, for the sake of the compiler knowing what you're doing:

import java.util.function.*;

class Test {
    public static void main(String[] args) {
        Function<String, Integer> function = asFunction(String::length).andThen(n -> n * 2);
        System.out.println(function.apply("foo"));
    }

    public static <T1, T2> Function<T1, T2> asFunction(Function<T1, T2> function) {
        return function;     
    }
}