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

标签 java java-8 java-stream

我有一个自定义类 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/

相关文章:

java - 无法使用 Apache POI 3.13 解析 CTDataModel

java - 将 ExoPlayer 中播放的视频打开到外部播放器 Intent 中

java - hashmap、java8、null/empty 检查

Java 8 函数式接口(interface),无参数,无返回值

java - 流 : Calculate the difference of totals in one go

java - 如何在使用流比较 map 时处理 null - Java?

java - 错误的数据类型 - 泛型

Java 泛型,检测超出范围的字节

java - 过滤器中的顺序 - 这重要吗?

java - 处理 Set<Foo> 的元素并使用流创建 Set<Bar>