There are multiple ways to generate the list from 1 to N or M to N in Java. We will look at 3 with various versions of Java.

Using Simple For Loop

Just iterate from 1 to N in for a loop and add it to the list.

int n = 10;
List<Integer> list = new ArrayList<>(n);
// 1 to n (inclusive)
for (int i = 1; i <= n; i++) {
    list.add(i);
}

Using IntStream - Java 8

Using IntStream’s range for end exclusive and rangeClosed for end inclusive. Here is how.

int n = 10;
// 1 to 9 (n is excusive)
List<Integer> list = IntStream.range(1, n)
        .boxed()
        .collect(Collectors.toList());

// 1 to 10 (n inclusive)
List<Integer> list = IntStream.rangeClosed(1, n)
        .boxed()
        .collect(Collectors.toList());

Using IntStream - Java 16 and Above

with Java 16 you can remove the collect method from streaming and instead use toList it directly. here is the rewritten version of the above code.

int n = 10;
// 1 to 9 (n is excusive)
List<Integer> list = IntStream.range(1, n)
        .boxed()
        .toList();

// 1 to 10 (n inclusive)
List<Integer> list = IntStream.rangeClosed(1, n)
        .boxed()
        .toList();

You can also read Stream API: The Hero Without a Cape and Functional Interfaces in Java to know more about Stream API