在方法[重复项]中使用通用谓词和函数

问题描述 投票:0回答:1

我在这里对泛型还不陌生,希望获得一些帮助。

我正在尝试使用泛型Predicate,泛型java.util Function,泛型List作为参数来创建泛型方法。方法是这样的:

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).

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

java function generics java-8 predicate
1个回答
0
投票

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

如果将mapper更改为Function<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;
}
© www.soinside.com 2019 - 2024. All rights reserved.