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());