java:不兼容类型:推理变量T具有不兼容的边界等式约束:下界:java.util.List<>

时间:2017-01-18 12:11:30

标签: java java-8 java-stream

我尝试从流中获取列表,但我有一个例外。

这是带有对象列表的Movie对象。

$this->registerJs('
    $(".xxxxxxx").show();
    $("[name=rd_id]").change(function(){
        if($(this).val() == 0) {
            $(".xxxxxxx").hide();
        } else {
            $(".xxxxxxx").show();
        }
    });
');

这是MovieTrans:

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

我在列表中添加元素:

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

2 个答案:

答案 0 :(得分:13)

<{p>}中的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());

答案 1 :(得分:8)

表达式的类型为List<List<MovieTrans>>:它是getMovieTranses方法结果的串联。

改为使用flatMap

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