java8 Steam实战

java8 Steam实战

假定选定一组专辑,找出其中所有长度大于1分钟的曲目名称

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

第一步要修改的是for循环.

    public Set findLongTracks(List albums) {
        HashSet trackNames = new HashSet();
        albums.stream()
          .forEach(album->{
            album.getTracks()
              .forEach(track ->{
                if(track.getLength()>60){
                  String name = track.getName();
                  trackNames.add(name);
                }
              })
          });
      return trackNames;
    }

第二步使用Stream操作

    public Set findLongTracks(List albums) {
        HashSet trackNames = new HashSet();
        albums.stream()
          .forEach(album->{
            album.getTracks()
              .filter(track -> track.getLength()>60)
              .map(track -> track.getName())
              .forEach(name -> trackNames.add(name));
          });
      return trackNames;
    }

第三步,将川籍转化成一个曲目的Stream,这里使用flatMap操作,把多个Stream合并成一个Stream并返回.

    public Set findLongTracks(List albums) {
        HashSet trackNames = new HashSet();
        albums.stream()
          .flatMap(album->album.getTracks())
          .filter(track -> track.getLength()>60)
          .map(track -> track.getName())
          .forEach(name -> trackNames.add(name));
      return trackNames;
    }

第四步,Stream中有collect操作可以将Stream中的值转换成一个列表

    public Set findLongTracks(List albums) {
       return albums.stream()
          .flatMap(album->album.getTracks())
          .filter(track -> track.getLength()>60)
          .map(track -> track.getName())
          .forEach(name -> trackNames.add(name))
          .collect(toSet());
    }

你可能感兴趣的:(java8 Steam实战)