2017-01-18 84 views
5

我嘗試獲得從流的列表,但我有一個例外。java的:不兼容的類型:推斷變量T具有不相容界限等式約束:下界:java.util.List的<>

這裏是一個對象的列表影片對象。

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 

這裏是MovieTrans:

public class MovieTrans { 

    public String text; 

    public MovieTrans(String text){ 
     this.text = text; 
    } 
    getter and setter 

我添加的元素的列表:

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()); 

我有這個編譯器錯誤:

Error:(44, 95) java: incompatible types: inference variable T has incompatible bounds 
    equality constraints: MovieTrans 
    lower bounds: java.util.List<MovieTrans> 

回答

10

map通話在

movies.stream().map(Movie::getMovieTranses) 

一個Stream<Movie>轉換爲Stream<List<MovieTrans>>,你可以收集到List<List<MovieTrans>>,而不是一個List<MovieTrans>

爲了得到一個List<MovieTrans>,使用flatMap

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

類型的表達式是List<List<MovieTrans>>:它是getMovieTranses方法的結果的串聯。

使用flatMap代替:

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

這是不可能要調用的方法作爲參考在flatMap參數。我用米做 - > m.getMovieTranses()流() – emoleumassi

+2

@emoleumassi編輯。 –

相關問題