gpt4 book ai didi

java - "error: incompatible types: inference variable R has incompatible bounds"单行flatMap流

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:58 24 4
gpt4 key购买 nike

我有一个自定义类 Custom .

public class Custom {

private Long id;

List<Long> ids;

// getters and setters
}

现在我有 List<Custom>对象。我想转换 List<Custom>进入List<Long> .我编写了如下代码,它运行良好。

    List<Custom> customs = Collections.emptyList();
Stream<Long> streamL = customs.stream().flatMap(x -> x.getIds().stream());
List<Long> customIds2 = streamL.collect(Collectors.toList());
Set<Long> customIds3 = streamL.collect(Collectors.toSet());

现在我将 line2 和 line3 组合成一行,如下所示。

    List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());

现在,这段代码没有编译,我遇到了错误 -

    error: incompatible types: inference variable R has incompatible bounds
List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());
^
equality constraints: Set<Long>
upper bounds: List<Long>,Object
where R,A,T are type-variables:
R extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
T extends Object declared in interface Stream

如何转换 List<Custom>进入Set<Long>List<Long>正确

最佳答案

你可以这样做:

List<Custom> customs = Collections.emptyList();
Set<Long> customIdSet = customs.stream()
.flatMap(x -> x.getIds().stream())
.collect(Collectors.toSet()); // toSet and not toList

你得到编译器错误的原因是你使用了不正确的 Collector它返回一个 List 而不是 Set ,这是您将其分配给 Set<Long> 的变量时预期的返回类型类型。

关于java - "error: incompatible types: inference variable R has incompatible bounds"单行flatMap流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com