java8函数式编程3

从双层循环中筛选出目标,用到Stream API包括:

flatMap : 用于Stream替换值,然后将多个Stream连接成一个Stream

filter : 遍历数据并检查其中的元素

map:将一个流中的值转换成一个新的流

例如: 从不同专辑中找出歌曲时长超过1分钟的歌曲名称(1张专辑包含多个歌曲)

1.先准备测试数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
    }
}

  

 

posted @   低调的小白  阅读(221)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2019-04-23 通过java代码往mysql数据库中写入日期相关数据少13个小时
2019-04-23 java8新的时间日期库及使用示例
2018-04-23 Spring 自带的定时任务Scheduled
点击右上角即可分享
微信分享提示