0

How can I generate an array of specified length by a method?

In short, what's an elegant replacement of this code:

Result generate() {
    // logic
}

Result[] results(int length) {
    Result[] results = new Result[length];
    for (int i = 0; i < results.length; i++) results[i] = generate();
    return results;
}
3
  • What you don't like in this solution? Pretty and neat. Commented Jun 27, 2015 at 14:45
  • 1
    With Java 8 : return IntStream.range(0, length).mapToObj(i -> generate()).toArray(Result[]::new);. Whether it is more readable/elegant or not is up to the reader. Commented Jun 27, 2015 at 14:50
  • @david.lucky I was looking for exactly what has Pshemo posted. Commented Jun 27, 2015 at 15:05

1 Answer 1

4

Since Java 8 instead of

for (int i = 0; i < results.length; i++) results[i] = generate();

you can use

Arrays.setAll(results, i -> generate());

You can also remove explicitly generating new Result[length] and let it be handled by stream

return IntStream.range(0, length).mapToObj(i->generate()).toArray(Result[]::new);

or probably more readable (but as Brian Goetz mentioned: with worse parallel performance compared to range version)

return Stream.generate(this::generate).limit(length).toArray(Result[]::new);

But don't confuse setAll(array, generator) with fill(array, element) method. fill will fill entire array with single element you passed while setAll will use generator to generate new element for each index in array.

Example:

static AtomicInteger ai = new AtomicInteger();
static int generate() {
    return ai.incrementAndGet();
}

public static void main(String[] args) {

    int[] result = new int[10];
    Arrays.fill(result, generate());
    System.out.println(Arrays.toString(result));

    Arrays.setAll(result, i->generate());
    System.out.println(Arrays.toString(result));

}

Output:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Sign up to request clarification or add additional context in comments.

2 Comments

Your first suggestion is the best, in my opinion.
@RedRoboHood I also like it, but I am not sure what approach OP is looking for so I added few more options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.