java8 Steam实战

作者: 罗志贇 | 来源:发表于2017-12-13 01:02 被阅读0次

    java8 Steam实战

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

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

    第二步使用Stream操作

        public Set<String> findLongTracks(List<Album> albums) {
            HashSet<Album> trackNames = new HashSet<Album>();
            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<String> findLongTracks(List<Album> albums) {
            HashSet<Album> trackNames = new HashSet<Album>();
            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<String> findLongTracks(List<Album> 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实战

        本文链接:https://www.haomeiwen.com/subject/pyioixtx.html