First off, you should capture this functionality in a dedicated method, rather than in the class' main method.
Secondly, I'm not sure why you want an array of String
. I don't know the context, but as you're already calculating with speeds, it seems likely you'll calculate more with them further on, and you'll want them to numberbe numbers again.
Next, your method of doing this is appending everything in one giant String
, and then splitting it again, after dealing with an unnecessary separator at the end. Looks like a lot of work for nothing. You can just add everything to an array directly (you'll have to precalculate its size beforehand though)
Java 8 has IntStream
, which is ideal for this task. It enables the one-liner you're looking for.
private int[] allSpeeds(int lower, int upper, int step) {
return IntStream.iterate(lower, i -> i + step)
.limit(Math.max(0, ((upper - lower) / step) + 1)) // limit to the needed size, ensure this value cannot be negative
.toArray();
}