1. Overview
In this tutorial, we'll explore different ways of listing sequences of numbers within a range.
2. Listing Numbers in a Range
2.1. Traditional for Loop
We can use a traditional for loop to generate numbers in a specified range:
public List<Integer> getNumbersInRange(int start, int end) { List<Integer> result = new ArrayList<>(); for (int i = start; i < end; i++) { result.add(i); } return result; }
The code above will generate a list containing numbers from start (inclusive) to end (exclusive).
2.2. JDK 8 IntStream.range
IntStream, introduced in JDK 8, can be used to generate numbers in a given range, alleviating the need for a for loop:
public List<Integer> getNumbersUsingIntStreamRange(int start, int end) { return IntStream.range(start, end) .boxed() .collect(Collectors.toList()); }
2.3. IntStream.rangeClosed
In the previous section, the end is exclusive. To get numbers in a range where the end is inclusive, there's IntStream.rangeClosed:
public List<Integer> getNumbersUsingIntStreamRangeClosed(int start, int end) { return IntStream.rangeClosed(start, end) .boxed() .collect(Collectors.toList()); }
2.4. IntStream.iterate
The previous sections used a range to get a sequence of numbers. When we know how many numbers in a sequence is needed, we can utilize the IntStream.iterate:
public List<Integer> getNumbersUsingIntStreamIterate(int start, int limit) { return IntStream.iterate(start, i -> i + 1) .limit(limit) .boxed() .collect(Collectors.toList()); }
Here, the limit parameter limits the number of elements to iterate over.
3. Conclusion
In this article, we saw different ways of generating numbers within a range.
Code snippets, as always, can be found over on GitHub.