Java流映射(..)-传递自定义Function时出错,但接受methodReference



为了代码的可读性,我正在创建自定义函数接口,同时将其作为map(...)中的映射器传递,编译错误即将到来。需要帮助。下面的例子针对这个问题进行了简化。例如

@FunctionalInterface
public interface Try<K,T> {
public K apply(T t);
}

public class Concrete{
//example
public static String checkFunc(Integer integer) {
return "Vivek";
}
}
public class CustomTest {
public static void main(String[] args) {

List<Integer> integers = Arrays.asList(1,2,3);

Try<String,Integer> try1 = Concrete::checkFunc;

integers.parallelStream().map(try1); // compile error
//The method map(Function<? super Integer,? extends R>) in the type Stream<Integer> is not 
//applicable for the arguments (Try<String,Integer>)
integers.parallelStream().map(Concrete::checkFunc); // this is perfectly fine
}

}

我正试着把上面的东西传给mapper。如何正确地做到这一点?

必须传入实现java.util.function.Function的东西。您有两个主要选择:

  • 使Try扩展Function
  • Try转换为Function,例如map(try1::apply)

您无法绕过将Function传递给map的需要。

最新更新