首页 > 解决方案 > 在方法中使用泛型谓词和函数

问题描述

我对这里的仿制药相当陌生,需要一些帮助。

我正在尝试使用 Generic Predicate、 Generic java.util Function、 GenericList作为参数创建一个 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).

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

标签: javafunctiongenericsjava-8predicate

解决方案


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

如果您更改mapperFunction<T,T> 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;
}

推荐阅读