
How to Generate List from 1 to N in Java
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. ...




