import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
public class RangeListInitializer {
public static void main(String[] args) {
int start = 1;
int end = 10;
// 1. Standard Streams approach (Mutable ArrayList result)
List<Integer> mutableList = createMutableRangeList(start, end);
System.out.println("Mutable List [1, 10]: " + mutableList);
// 2. Unmodifiable List approach (Read-only view)
List<Integer> unmodifiableList = createUnmodifiableRangeList(start, end);
System.out.println("Unmodifiable List [1, 10]: " + unmodifiableList);
// 3. Pre-sized ArrayList loop approach (Optimal performance for custom logic)
List<Integer> loopList = createRangeListWithLoop(start, end);
System.out.println("Loop List [1, 10]: " + loopList);
}
/**
* Creates a mutable List<Integer> containing a sequential range of numbers [start, end].
* Uses IntStream.rangeClosed and boxed() to map primitives to Integer objects.
*
* @param start The starting integer (inclusive)
* @param end The ending integer (inclusive)
* @return A mutable List containing values from start to end
*/
public static List<Integer> createMutableRangeList(int start, int end) {
// IntStream.rangeClosed handles range generation.
// boxed() converts IntStream to Stream<Integer>.
// toList() creates an unmodifiable list; wrapping in ArrayList makes it mutable.
return new ArrayList<>(
IntStream.rangeClosed(start, end)
.boxed()
.toList()
);
}
/**
* Creates an immutable, unmodifiable List<Integer> containing a range of numbers.
* Ideal when the returned list should not be modified by caller code.
*
* @param start The starting integer (inclusive)
* @param end The ending integer (inclusive)
* @return An unmodifiable List containing values from start to end
*/
public static List<Integer> createUnmodifiableRangeList(int start, int end) {
return IntStream.rangeClosed(start, end)
.boxed()
.toList(); // Returns an unmodifiable List
}
/**
* Creates a List<Integer> using a classical imperative loop with initial capacity pre-allocated.
* Minimizes memory re-allocations during population.
*
* @param start The starting integer (inclusive)
* @param end The ending integer (inclusive)
* @return A pre-sized List containing values from start to end
*/
public static List<Integer> createRangeListWithLoop(int start, int end) {
int count = end - start + 1;
// Pre-size the ArrayList to avoid internal array resizing overhead
List<Integer> list = new ArrayList<>(count);
for (int i = start; i <= end; i++) {
list.add(i);
}
return list;
}
}
/*
run:
Mutable List [1, 10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Unmodifiable List [1, 10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Loop List [1, 10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*/