Using a stream to iterate n times instead of using a for loop to create n items

前端 未结 2 981
北恋
北恋 2021-02-05 00:22

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

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


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 01:03

    You could use Stream#generate with limit:

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

提交回复
热议问题