java: incompatible types: inference variable T has incompatible bounds equality constraints: lower bounds: java.util.List<>

余生颓废 提交于 2019-12-09 11:49:58

问题


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.

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:

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>

回答1:


The map call in

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>.

To get a single List<MovieTrans>, use flatMap :

List<MovieTrans> movieTransList1 = 
    movies.stream()
          .flatMap(m -> m.getMovieTranses().stream())
          .collect(Collectors.toList());



回答2:


The type of your expression is List<List<MovieTrans>>: it's the concatenation of the results of the getMovieTranses method.

Use flatMap instead:

List<MovieTrans> movieTransList1 = movies.stream()
    .flatMap(m -> m.getMovieTranses().stream())
    .collect(Collectors.toList());


来源:https://stackoverflow.com/questions/41719097/java-incompatible-types-inference-variable-t-has-incompatible-bounds-equality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!