在Java 8中使用流中的过滤器方法时出错

时间:2017-09-09 00:58:21

标签: java-8 java-stream

使用过滤方法时出错。该错误表明过滤器未定义类型List。我无法弄清楚我的IDE是否未识别过滤器方法或我的代码存在问题。任何帮助将不胜感激。我已经检查了我的合规水平1.8。请帮我弄清楚可能出现的问题。

public class TestJava8 {

    public static void main(String[] args) {

    Track track1 = new Track("master1", 7);
    Track track2 = new Track("master2", 8);
    Track track3 = new Track("master3", 9);
    Track track4 = new Track("master4", 10);
    Track track5 = new Track("master5", 11);

    Track track6 = new Track("master6", 7);
    Track track7 = new Track("master7", 8);
    Track track8 = new Track("master8", 9);
    Track track9 = new Track("master9", 10);
    Track track10 = new Track("master10", 11);
    Track track11 = new Track("master11", 12);

    List<Track> tracks1 = new ArrayList<>();
    List<Track> tracks2 = new ArrayList<>();

    tracks1.add(track1);
    tracks1.add(track2);
    tracks1.add(track3);
    tracks1.add(track4);
    tracks1.add(track5);

    tracks2.add(track6);
    tracks2.add(track7);
    tracks2.add(track8);
    tracks2.add(track9);
    tracks2.add(track10);
    tracks2.add(track11);

    Album album1 = new Album(tracks1);
    Album album2 = new Album(tracks2);

    List<Album> albums = new ArrayList<>();

    albums.add(album1);
    albums.add(album2);

    Set<String> tracksFound = findLongTrackss(albums);

    tracksFound.forEach(track -> System.out.println(track));

}


public static Set<String> findLongTracks(List<Album> albums) {
    Set<String> trackNames = new HashSet<>();
    for (Album album : albums) {
        for (Track track : album.getTracks()) {
            if (track.getLength() > 6) {
                String name = track.getName();
                trackNames.add(name);
            }
        }
    }
    return trackNames;
}

public static Set<String> findLongTrackss(List<Album> albums) {

    Set<String> trackNames = new HashSet<>();

    albums.stream()
    .forEach(album -> {
        album.getTracks()
             .filter(track -> track.getLength() > 8)// I am getting an error here
             .map(track -> track.getName())
             .forEach(name -> trackNames.add(name));
        });

    return trackNames;

}

}

1 个答案:

答案 0 :(得分:0)

你应该阅读the documentation并向下滚动到Side-Effects,有一个非常接近你的例子。你应该这样写你的流:

Set<String> trackNames = albums.stream()
            .flatMap(a -> a.getTracks().stream()
                    .filter(track -> track.getLength() > 8)
                    .map(Track::getName))
            .collect(Collectors.toSet());