Reputation: 740
The method should return long stream from -n to n except 0. For n = 3 the stream should be -3, -2, -1, 1, 2, 3.
What approach is better?
(1)
public static LongStream getLongStream(int n) {
return n == 0
? LongStream.empty()
: LongStream.concat(
LongStream.range(-n, 0),
LongStream.rangeClosed(1, n));
}
(2)
public static LongStream getLongStream(int n) {
return LongStream.concat(
LongStream.range(-n, 0),
LongStream.rangeClosed(1, n));
}
Thank you for your comments. I suppose that the second variant is the best way to produce such streams.
Upvotes: 0
Views: 235
Reputation: 86272
It will be a matter of taste. Take the version that you and in particular your readers — those maintaining your code after you — will prefer. Here’s yet an option. I like to make your requirement one number should be skipped more explicit in the code.
public static LongStream getLongStream(int n) {
return LongStream.rangeClosed(-n, n).filter(i -> i != 0);
}
To try it out:
System.out.println(getLongStream(3).boxed().collect(Collectors.toList()));
Output:
[-3, -2, -1, 1, 2, 3]
It’s less runtime efficient than your versions. Holger’s comment seems to indicate that the difference may be great for large values of n
, though depending on what you are using the stream for. If concerned, you will need to make your own measurements.
Upvotes: 2
Reputation: 740
I think that in terms of optimization the second variant is the best one.
public static LongStream getLongStream(long n) {
return LongStream.concat(
LongStream.range(-n, 0),
LongStream.rangeClosed(1, n));
}
Upvotes: 1