Map 和 orElse 返回不同的子类型

我有两个功能 - 一个返回Set<String>,另一个返回List<String>。


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

    ....

}


private static Set<String> getStringSet() {

    ....

}

现在,我有一个返回 a 的函数Collection<String>,它会根据特定条件依次调用上述函数。我想做这样的事情:


private static Collection<String> getStringCollection() {

    Optional<String> factor = getFactor();

    return factor.filter(LambdaTest::someCondition)

            .map(LambdaTest::getStringList)

            .orElse(getStringSet());

}

但我得到这个错误


错误:(24, 37) java: 类型不兼容:java.util.Set 无法转换为 java.util.List


我能理解这里发生了什么。但是,有没有一种方法可以在不进行像这样精心设计的 if-else 语句的情况下实现类似的效果呢?


private static Collection<String> getStringCollection() {

    Optional<String> factor = getFactor();


    if(factor.isPresent() && someCondition(factor.get())) {

        return getStringList(factor.get());

    }


    return getStringSet();

}


慕容3067478
浏览 117回答 2
2回答

肥皂起泡泡

您可以使用通用类型规范来强制getStringList将其视为Collection<String>:return&nbsp;factor.filter(LambdaTest::someCondition) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.<Collection<String>>&nbsp;map(LambdaTest::getStringList) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElse(getStringSet());

达令说

不确定这是否明显并在问题的后半部分说明,但您还可以做的是更改方法的签名getStringList以返回 a Collection<String>,保持其实现与之前相同。这样完整的实现看起来像:Collection<String> getStringList(final String factor) { ... }Set<String> getStringSet() { ... }private Collection<String> getStringCollection() {&nbsp; &nbsp; Optional<String> factor = getFactor();&nbsp; &nbsp; return factor.filter(this::someCondition)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(this::getStringList)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElseGet(this::getStringSet);}另一种选择是初始化SetinorElse以返回Listusing new ArrayList<>:private Collection<String> getStringCollection() {&nbsp; &nbsp; Optional<String> factor = getFactor();&nbsp; &nbsp; return factor.filter(this::someCondition)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(this::getStringList)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElse(new ArrayList<>(getStringSet()));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java