java8函数式编程3
从双层循环中筛选出目标,用到Stream API包括:
flatMap : 用于Stream替换值,然后将多个Stream连接成一个Stream
filter : 遍历数据并检查其中的元素
map:将一个流中的值转换成一个新的流
例如: 从不同专辑中找出歌曲时长超过1分钟的歌曲名称(1张专辑包含多个歌曲)
1.先准备测试数据
package com.ieou.h2; import java.util.ArrayList; import java.util.List; /** * created by wyz on 2020/4/23 */ public class Album { private List<Track> track; public static class Track { private String name; private Integer length; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } } public List<Track> getTrack() { return track; } public void setTrack(List<Track> track) { this.track = track; } public List<Album> init() { List<Album> albums = new ArrayList<>(); List<Track> tracks = new ArrayList<>(); Track track = new Track(); track.setName("a"); track.setLength(10); tracks.add(track); Track track1 = new Track(); track1.setName("b"); track1.setLength(300); tracks.add(track1); Album album = new Album(); album.setTrack(tracks); albums.add(album); return albums; } }
2.
package com.ieou.h2; import java.util.List; import java.util.Set; import static java.util.stream.Collectors.toSet; /** * created by wyz on 2020/4/23 */ public class TestJava8 { public static void main(String[] args) { /** * 从不同专辑中找出歌曲时长超过1分钟的歌曲名称(1张专辑包含多个歌曲) */ List<Album> albums = new Album().init(); Set<String> set = albums.stream(). flatMap(album -> album.getTrack().stream()). //先把所有专辑的歌曲合并到一个列表中 filter(track -> track.getLength() > 60). //筛选出时长超过60的歌曲 map(Album.Track::getName).collect(toSet()); //找出符合条件的歌曲名称并放入set集合 System.out.println(set); } }
hello world!!!