java:不兼容的类型:推理变量 T 具有不兼容的边界等式约束:下限:java.util.List<>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41719097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java: incompatible types: inference variable T has incompatible bounds equality constraints: lower bounds: java.util.List<>
提问by emoleumassi
i try to get a list from a stream but i have an exception.
我尝试从流中获取列表,但我有一个例外。
Here is the Movie object with a list of an object.
这是带有对象列表的 Movie 对象。
public class Movie {
private String example;
private List<MovieTrans> movieTranses;
public Movie(String example, List<MovieTrans> movieTranses){
this.example = example;
this.movieTranses = movieTranses;
}
getter and setter
Here is the MovieTrans:
这是 MovieTrans:
public class MovieTrans {
public String text;
public MovieTrans(String text){
this.text = text;
}
getter and setter
i add the element in the lists:
我在列表中添加元素:
List<MovieTrans> movieTransList = Arrays.asList(new MovieTrans("Appel me"), new MovieTrans("je t'appel"));
List<Movie> movies = Arrays.asList(new Movie("movie played", movieTransList));
//return a list of MovieTrans
List<MovieTrans> movieTransList1 = movies.stream().map(Movie::getMovieTranses).collect(Collectors.toList());
i have this compiler error:
我有这个编译器错误:
Error:(44, 95) java: incompatible types: inference variable T has incompatible bounds
equality constraints: MovieTrans
lower bounds: java.util.List<MovieTrans>
采纳答案by Eran
The map
call in
该map
呼叫
movies.stream().map(Movie::getMovieTranses)
converts a Stream<Movie>
to a Stream<List<MovieTrans>>
, which you can collect into a List<List<MovieTrans>>
, not a List<MovieTrans>
.
将 a 转换Stream<Movie>
为 a Stream<List<MovieTrans>>
,您可以将其收集为 a List<List<MovieTrans>>
,而不是 a List<MovieTrans>
。
To get a single List<MovieTrans>
, use flatMap
:
要获得单个List<MovieTrans>
,请使用flatMap
:
List<MovieTrans> movieTransList1 =
movies.stream()
.flatMap(m -> m.getMovieTranses().stream())
.collect(Collectors.toList());
回答by Andy Turner
The type of your expression is List<List<MovieTrans>>
: it's the concatenation of the results of the getMovieTranses
method.
表达式的类型是List<List<MovieTrans>>
:它是getMovieTranses
方法结果的串联。
Use flatMap
instead:
使用flatMap
来代替:
List<MovieTrans> movieTransList1 = movies.stream()
.flatMap(m -> m.getMovieTranses().stream())
.collect(Collectors.toList());