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

前端 未结 2 980
北恋
北恋 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 00:55

    If you know n in advance, I think it's more idiomatic to use one of the stream sources that creates a stream that is known to have exactly n elements. Despite the appearances, using limit(10) doesn't necessarily result in a SIZED stream with exactly 10 elements -- it might have fewer. Having a SIZED stream improves splitting in the case of parallel execution.

    As Sotirios Delimanolis noted in a comment, you could do something like this:

    List<MyClass> list = IntStream.range(0, n)
        .mapToObj(i -> new MyClass())
        .collect(toList());
    

    An alternative is this, though it's not clear to me it's any better:

    List<MyClass> list2 = Collections.nCopies(10, null).stream()
        .map(o -> new MyClass())
        .collect(toList());
    

    You could also do this:

    List<MyClass> list = Arrays.asList(new MyClass[10]);
    list.replaceAll(o -> new MyClass());
    

    But this results in a fixed-size, though mutable, list.

    0 讨论(0)
  • 2021-02-05 01:03

    You could use Stream#generate with limit:

    Stream.generate(MyClass::new).limit(10);
    
    0 讨论(0)
提交回复
热议问题