Using Generic Predicate and Function in a method

Aron :

I'm fairly new to generics here and would like some assistance.

I'm trying to create a Generic method with a Generic Predicate, a Generic java.util Function, a Generic List as arguments. The method is like this:

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;
    }

I'm getting an error on the orElse(elseResult) method. This is the error -

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

I'm not exactly sure as to what this error is about. So could someone tell me what I'm doing wrong here? Thanks.

Eran :

Your mapper can return anything, so your orElse method will not necessarily return a T.

If you change your mapper to Function<T,T> mapper, your code will pass compilation.

If you want your mapper to be able to return a different type, add a second type argument:

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=344718&siteId=1