Java Stream map(...) - 传递自定义函数时出错,尽管接受 methodReference

Viv*_*mar 1 java functional-programming java-stream

为了代码可读性,我正在创建自定义函数接口,同时将其作为映射器传递给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

    }
     
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试传递类似上面的映射器。如何正确地做到这一点?

Lou*_*man 6

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

  • 使Try延长Function
  • 转换Try为 a Function,例如map(try1::apply)

您无法绕过传递 a Functionto的需要map