Lets say I have an integer for example 6350
. How can I create intervals of size N
(lets say 500) that results in the following ranges:
[0, 500, 1000, 1500, 2000 ... 6000, 6350]
Lets say I have an integer for example 6350
. How can I create intervals of size N
(lets say 500) that results in the following ranges:
[0, 500, 1000, 1500, 2000 ... 6000, 6350]
The most obvious java only (no third parties) solution:
int max = 6350;
int N = 500;
List<Integer> result = new ArrayList<>();
for(int i = 0 ; i < max; i+=N) {
result.add(i);
}
result.add(max);
The result
array list should look like exactly as you’ve posted in the question
You can use IntStream
int limit = 6350;
int interval = 500;
int[] array = IntStream.iterate(0, i -> i < limit, i -> i + interval).toArray();
Using streams as a replacement of for
loop:
final int MAX = 6350, INC = 500;
Stream.concat(
Stream.iterate(0, i -> i < MAX, i -> i + INC),
Stream.of(MAX)
)
.collect(Collectors.toList()) // may be skipped
.forEach(System.out::println);
prints sequence:
500
1000
1500
2000
2500
3000
3500
4000
4500
5000
5500
6000
6350