import java.util.Arrays;
import java.util.stream.IntStream;
public class RangeArrayInitializer {
public static void main(String[] args) {
int start = 1;
int end = 10;
// 1. Declarative approach using Streams (Inclusive of 'end')
int[] streamArray = createRangeWithStream(start, end);
System.out.println("Stream Range [1, 10]: " + Arrays.toString(streamArray));
// 2. High-performance approach using parallel operations for large datasets
int[] parallelArray = createLargeRangeParallel(1, 10);
System.out.println("Parallel Range [1, 10]: " + Arrays.toString(parallelArray));
// 3. Imperative approach (Best for raw performance and memory efficiency)
int[] loopArray = createRangeWithLoop(start, end);
System.out.println("Loop Range [1, 10]: " + Arrays.toString(loopArray));
}
/**
* Creates an integer array containing a sequential range of numbers [start, end].
* Uses IntStream.rangeClosed to include the end boundary.
*
* @param start The starting integer (inclusive)
* @param end The ending integer (inclusive)
* @return An array containing values from start to end
*/
public static int[] createRangeWithStream(int start, int end) {
// IntStream.rangeClosed(start, end) generates values sequentially from start to end.
// .toArray() collects the stream elements into a primitive int[] array.
return IntStream.rangeClosed(start, end).toArray();
}
/**
* Creates an array filled in parallel using Arrays.setAll.
* Ideal for initializing very large arrays across multiple CPU cores.
*
* @param start The starting integer (inclusive)
* @param end The ending integer (inclusive)
* @return An array populated in parallel
*/
public static int[] createLargeRangeParallel(int start, int end) {
int size = end - start + 1;
int[] result = new int[size];
// setAll uses an index-based generator function (index -> value)
// parallelSetAll distributes the array population across available worker threads
Arrays.setAll(result, i -> start + i);
return result;
}
/**
* Traditional for-loop initialization.
* Offers the lowest possible overhead and optimal memory allocation.
*
* @param start The starting integer (inclusive)
* @param end The ending integer (inclusive)
* @return An array filled sequentially
*/
public static int[] createRangeWithLoop(int start, int end) {
int size = end - start + 1;
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = start + i;
}
return result;
}
}
/*
run:
Stream Range [1, 10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Parallel Range [1, 10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Loop Range [1, 10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*/