To create a list of integers in a range in Java, you can use the IntStream.range
method from the java.util.stream
package.
Here is an example of how to create a list of integers from 1 to 10:
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { List<Integer> list = IntStream.range(1, 11).boxed().collect(Collectors.toList()); System.out.println(list); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } }
This creates a stream of integers using the range
method, boxes the integers into Integer
objects using the boxed
method, and collects them into a List
using the collect
method.
You can also use the IntStream.rangeClosed
method to include the end of the range in the list. For example:
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { List<Integer> list = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList()); System.out.println(list); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } }