千家信息网

JAVA8的stream怎么使用

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,这篇文章主要讲解了"JAVA8的stream怎么使用",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"JAVA8的stream怎么使用"吧!扁平化处理对象
千家信息网最后更新 2025年02月01日JAVA8的stream怎么使用

这篇文章主要讲解了"JAVA8的stream怎么使用",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"JAVA8的stream怎么使用"吧!

扁平化处理

对象是这样的

import java.util.List;import lombok.Getter;import lombok.Setter;@Getter@Setterpublic class ResourceCache {    private Long id;    private Long pid;    private String code;    private String name;    private Boolean leaf;    /** 子菜单列表 **/    private List children;}

给定一个List的集合,要求输出Listid集合的结果

 List has = caches.stream().flatMap(c -> Stream.concat(Stream.of(c), c.getChildren().stream()))                                .flatMap(c -> Stream.concat(Stream.of(c), c.getChildren().stream()))                                .flatMap(c -> Stream.concat(Stream.of(c), c.getChildren().stream()))                                .flatMap(c -> Stream.concat(Stream.of(c), c.getChildren().stream()))                                .map(p -> p.getId())                                .collect(Collectors.toList());

其中ResourceCache嵌套了几层就用几次flatMap,其中有个小的点,用了Stream.concat,既保留自己也合并了下一级

感谢各位的阅读,以上就是"JAVA8的stream怎么使用"的内容了,经过本文的学习后,相信大家对JAVA8的stream怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

0