当flatMap流在一行中时,出现“错误:不兼容的类型:推理变量R具有不兼容的范围”

Raj*_*jan 6 java java-8 java-stream

我有一个习俗课Custom

public class Custom {

  private Long id;

  List<Long> ids;

  // getters and setters
}
Run Code Online (Sandbox Code Playgroud)

现在我有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());
Run Code Online (Sandbox Code Playgroud)

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

    List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)

现在,此代码未编译,并且出现了以下错误-

    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
Run Code Online (Sandbox Code Playgroud)

我怎么能转换List<Custom>Set<Long>List<Long>正确

Nam*_*man 5

你可以这样做:

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

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