Java Generate List From 1 to N
There are several ways to generate a list from 1 to n in Java.
Using a Loop
import java.util.ArrayList;
import java.util.List;
public class GenerateListFrom1ToNUsingLoopMain {
public static void main(String[] args) {
int n = 10;
List<Integer> list = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
list.add(i);
}
System.out.println(list); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Also, loop can be re-written as 0…N-1:
import java.util.ArrayList;
import java.util.List;
public class GenerateListFrom1ToNUsingLoopMain {
public static void main(String[] args) {
int n = 10;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(i + 1);
}
System.out.println(list); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Using IntStream
This example uses the Java Stream API for a more functional and concise approach.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class GenerateListFrom1ToNUsingIntStreamMain {
public static void main(String[] args) {
int n = 10;
List<Integer> list = IntStream.rangeClosed(1, n)
.boxed()
.collect(Collectors.toList());
System.out.println(list); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Since Java 16, there is Stream::toList method and last example can be simplified:
import java.util.stream.IntStream;
public class GenerateListFrom1ToNUsingIntStreamJava16Main {
public static void main(String[] args) {
int n = 10;
var list = IntStream.rangeClosed(1, n)
.boxed()
.toList();
System.out.println(list); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}