使用流迭代n次而不是使用for循环来创建n个项目 [英] Using a stream to iterate n times instead of using a for loop to create n items

查看:171
本文介绍了使用流迭代n次而不是使用for循环来创建n个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我要创建n个项目。在Java 8之前,我会写:

Say I want to create n items. Pre Java 8, I would write:

List<MyClass> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
    list.add(new MyClass());
}

是否有一种优雅的方式来使用流来创建n个项目?

我想到了这个:

Is there an elegant way to use a stream to create n items?
I thought of this:

List<MyClass> list = Stream.iterate(0, i -> i).limit(10)
    .map(o -> new MyClass()).collect(Collectors.toList());

是否有标准/更好的编码方式?

Is there a standard/better way of coding this?

请注意实际使用情况稍微复杂一些,使用流会更灵活,因为我可以立即通过一行中的其他函数抽取项目,甚至无需创建对列表,例如对它们进行分组:

Note that the actual usage is a bit more complex and using a stream would be more flexible because I can immediately pump the items through other functions in one line without even creating a reference to the list, for example grouping them:

Stream.iterate(0, i -> i).limit(10).map(o -> new MyClass())
    .collect(Collectors.groupingBy(...));


推荐答案

你可以使用 Stream#使用 rel =noreferrer> limit

You could use Stream#generate with limit:

Stream.generate(MyClass::new).limit(10);

这篇关于使用流迭代n次而不是使用for循环来创建n个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆