Map and orElse returning different subtypes

bdhar :

I have two functions - one returning Set<String> and another returning List<String>.

private static List<String> getStringList(final String factor) {
    ....
}

private static Set<String> getStringSet() {
    ....
}

Now, I have a function to return a Collection<String> which in turn calls the above functions based on a certain condition. I want to do something like this:

private static Collection<String> getStringCollection() {
    Optional<String> factor = getFactor();
    return factor.filter(LambdaTest::someCondition)
            .map(LambdaTest::getStringList)
            .orElse(getStringSet());
}

But I get this error

Error:(24, 37) java: incompatible types: java.util.Set cannot be converted to java.util.List

I can understand what's going on here. But is there a way to achieve something similar without doing an elaborate if-else statement like this?

private static Collection<String> getStringCollection() {
    Optional<String> factor = getFactor();

    if(factor.isPresent() && someCondition(factor.get())) {
        return getStringList(factor.get());
    }

    return getStringSet();
}
Mureinik :

You could use a generic type specification to force getStringList to be treated as a Collection<String>:

return factor.filter(LambdaTest::someCondition)
             .<Collection<String>> map(LambdaTest::getStringList)
             .orElse(getStringSet());

Guess you like

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