java 8中构建无限的stream

简介

在java中,我们可以将特定的集合转换成为stream,那么在有些情况下,比如测试环境中,我们需要构造一定数量元素的stream,需要怎么处理呢?

这里我们可以构建一个无限的stream,然后调用limit方法来限定返回的数目。

基本使用

先看一个使用Stream.iterate来创建无限Stream的例子:

    @Test
public void infiniteStream(){
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 1);
List<Integer> collect = infiniteStream
.limit(10)
.collect(Collectors.toList());
log.info("{}",collect);
}

上面的例子中,我们通过调用Stream.iterate方法,创建了一个0,1,2,3,4....的无限stream。

然后调用limit(10)来获取其中的前10个。最后调用collect方法将其转换成为一个集合。

看下输出结果:

INFO com.flydean.InfiniteStreamUsage - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

自定义类型

如果我们想输出自定义类型的集合,该怎么处理呢?

首先,我们定义一个自定义类型:

@Data
@AllArgsConstructor
public class IntegerWrapper {
private Integer integer;
}

然后利用Stream.generate的生成器来创建这个自定义类型:

    public static IntegerWrapper generateCustType(){
return new IntegerWrapper(new Random().nextInt(100));
} @Test
public void infiniteCustType(){
Supplier<IntegerWrapper> randomCustTypeSupplier = InfiniteStreamUsage::generateCustType;
Stream<IntegerWrapper> infiniteStreamOfCustType = Stream.generate(randomCustTypeSupplier); List<IntegerWrapper> collect = infiniteStreamOfCustType
.skip(10)
.limit(10)
.collect(Collectors.toList());
log.info("{}",collect);
}

看下输出结果:

INFO com.flydean.InfiniteStreamUsage - [IntegerWrapper(integer=46), IntegerWrapper(integer=42), IntegerWrapper(integer=67), IntegerWrapper(integer=11), IntegerWrapper(integer=14), IntegerWrapper(integer=80), IntegerWrapper(integer=15), IntegerWrapper(integer=19), IntegerWrapper(integer=72), IntegerWrapper(integer=41)]

总结

本文介绍了两个生成无限stream的例子。本文的代码learn-java-streams

欢迎关注我的公众号:程序那些事,更多精彩等着您!

更多内容请访问 www.flydean.com

最新文章

  1. Ubuntu14.04_64位使用过程
  2. placeholder 不支持IE修复
  3. salesforce 零基础学习(三十九) soql函数以及常量
  4. SQLite 增、删、改、查
  5. 【java】[转]标记接口和标记注解注解
  6. 使用虚幻引擎中的C++导论(一-生成C++类)
  7. HDU 1024 (不重叠m段最大和) Max Sum Plus Plus
  8. sysstat的基本用法
  9. centos 服务器配置(三) 之定时任务
  10. Navicat for mysql 远程连接 mySql数据库10061、1045错误问题 (转)
  11. centos7.2下安装mysql5.7,使用rpm包安装
  12. 51nod 1244 莫比乌斯函数之和(杜教筛)
  13. error C2448 函数样式初始值设定项类似函数定义
  14. Python视频人脸检测识别
  15. php的Memcached模块扩展
  16. Apache Spark 内存管理详解(转载)
  17. 微信小程序生成海报分享:canvas绘制文字溢出如何换行
  18. EF Migrations error: No connection string named &#39;MpDb&#39; could be found in the application config file.
  19. CF1131D Gourmet choice(并查集,拓扑排序)
  20. js获取地址栏信息

热门文章

  1. CentOS8中安装maven
  2. PTA数据结构与算法题目集(中文) 7-43字符串关键字的散列映射 (25 分)
  3. Shell:Day07.笔记
  4. 曹工说Redis源码(3)-- redis server 启动过程完整解析(中)
  5. C语言 文件操作(四)
  6. 汇编 RET 和 CALL
  7. Vue项目添加动态浏览器头部title
  8. 37 net 网络编程
  9. "一号标题"组件:&lt;h1&gt; —— 快应用组件库H-UI
  10. Chrome浏览器架构