【问题标题】:Using Generic Predicate and Function in a method [duplicate]在方法中使用通用谓词和函数[重复]
【发布时间】:2020-07-02 23:21:31
【问题描述】:

我对这里的泛型还很陌生,需要一些帮助。

我正在尝试使用 Generic Predicate、Generic java.util Function、Generic List 作为参数创建一个 Generic 方法。方法是这样的:

public static <T> T getValue(Predicate<? super Object> condition, Function<? super Object, ? extends Object> mapper, T elseResult, List<T> table) {
        T result = null;
        if (table != null)
            result = table.stream()
                    .filter(condition)
                    .map(mapper).findAny().orElse(elseResult); // Syntax error here.
        else
            result = elseResult;

        return (T) result;
    }

orElse(elseResult) 方法出现错误。这是错误 -

The method orElse(capture#1-of ? extends Object) in the type Optional<capture#1-of ? extends Object> is not applicable for the arguments (T).

我不确定这个错误是关于什么的。那么有人可以告诉我我在这里做错了什么吗?谢谢。

【问题讨论】:

  • static &lt;T&gt; T getValue(Predicate&lt;? super T&gt; condition, Function&lt;? super T, T&gt; mapper, T elseResult, List&lt;T&gt; table) 应该为你做。

标签: java function generics java-8 predicate


【解决方案1】:

您的mapper 可以返回任何内容,因此您的orElse 方法不一定会返回T。

如果您将mapper 更改为Function&lt;T,T&gt; mapper,您的代码将通过编译。

如果您希望映射器能够返回不同的类型,请添加第二个类型参数:

public static <T,S> S getValue(Predicate<? super Object> condition, Function<T,S> mapper, S elseResult, List<T> table) {
    S result = null;
    if (table != null)
        result = table.stream()
                .filter(condition)
                .map(mapper).findAny().orElse(elseResult);
    else
        result = elseResult;

    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    相关资源
    最近更新 更多