0

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]
fareed
  • 3,034
  • 6
  • 37
  • 65
  • Does this answer your question? [Java: how can I split an ArrayList in multiple small ArrayLists?](https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists) – azro Jun 15 '20 at 21:00

3 Answers3

2

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

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
1

You can use IntStream

    int limit = 6350;
    int interval = 500;
    int[] array = IntStream.iterate(0, i -> i < limit, i -> i + interval).toArray();
0xh3xa
  • 4,801
  • 2
  • 14
  • 28
1

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
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42