当前位置:网站首页>One bite of Stream(6)
One bite of Stream(6)
2022-07-20 19:44:00 【程序员·小李】
Stream的生成
前面我们都在讲如何过滤、匹配,统计、映射、收集等等,接下来看看怎么样生成Stream
1. Stream.of(T...)
Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");
Stream.of()可以生成流,参数会逐个填充进去。
2. Arrays.stream(T[])
int[] numbers = {2, 3, 5, 7, 11, 13};
int sum = Arrays.stream(numbers).sum();
Arrays.stream()在创建流时,传入数组对象,基础类型会生成对应的IntStream、LongStream、DoubleStream。
3. Files.lines()
long uniqueWords = 0;
try(Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())){
uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" "))).distinct().count();
}
catch(IOException e){
}
Files.lines()用于打开文件读取到流,每一行为一个字符串。
4. Stream.iterate()
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);
iterate会产生一个无界流(没有边界,如果不加控制就是死循环),这里使用limit控制了数量
两个入参,一个是初始值,第二个是递归算法,根据前一个值计算新的值。
5. Stream.generate()
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
generate(Supplier<T>)用外部提供的方法生成数据,也是无界流。
6. collection.stream()
List<Integer> list = new ArrayList<Integer>();
Stream<Integer> stream = list.stream();
边栏推荐
猜你喜欢
PCL calculates point cloud roughness
Redis implements distributed current limiting (learning notes
13 个实用的代码片断,建议收藏
PCL计算点云粗糙度
单元测试,写起来到底有多痛?你会了吗
Help enterprises' digital upgrading, and volcano engine releases cloud growth solutions
How to solve the problem of win11 Microsoft account login? Win11 Microsoft account login has been circling
Multi active architecture of King glory mall
How to uninstall the update patch for win11 22h2? Steps to uninstall the updated patch for win11 22h2
使用nvm安装node成功,安装npm失败(Error while downloading,TLS handshake timeout)
随机推荐
For a single document BCG program, why is the title of the toolbar set at the end of cmainframe:: oncreate? Why is it invalid?
Regular expressions from entry to entry
单元测试,写起来到底有多痛?你会了吗
NiO implements a simple group chat system
STL notes (XII): relevance container - set
[3D target detection] pointpillars (II)
jvm的启动过程
Win11 Excel文件变成白板图标怎么解决?
预交费功能
带新人心得
The B2B system of digital intelligence in the daily chemical industry simplifies the distribution process and improves the competitiveness of the supply chain of daily chemical enterprises
白宫正设法推动填补美国数十万个网络安全工作岗位
微信小程序怎么测试
DQL语句_查询表中指定的字段_以及指定的别名_以及字段去重
IO file input / output stream
Multi active architecture of King glory mall
低代码平台搭建跨部门沟通系统案例分析
Win11打印机文档被挂起如何解决?
Dc-3-range practice
oh my god