use of com.annimon.stream.function.LongSupplier in project Lightweight-Stream-API by aNNiMON.
the class RandomCompat method longs.
/**
* Returns an effectively unlimited stream of pseudorandom {@code long}
* values, each conforming to the given origin (inclusive) and bound (exclusive)
*
* @param randomNumberOrigin the origin (inclusive) of each random value
* @param randomNumberBound the bound (exclusive) of each random value
* @return a stream of pseudorandom {@code long} values,
* each with the given origin (inclusive) and bound (exclusive)
* @throws IllegalArgumentException if {@code randomNumberOrigin}
* is greater than or equal to {@code randomNumberBound}
*/
public LongStream longs(final long randomNumberOrigin, final long randomNumberBound) {
if (randomNumberOrigin >= randomNumberBound) {
throw new IllegalArgumentException();
}
return LongStream.generate(new LongSupplier() {
private final long bound = randomNumberBound - randomNumberOrigin;
private final long boundMinus1 = bound - 1;
@Override
public long getAsLong() {
long result = random.nextLong();
if ((bound & boundMinus1) == 0L) {
// power of two
result = (result & boundMinus1) + randomNumberOrigin;
} else if (bound > 0L) {
// reject over-represented candidates
// ensure nonnegative
long u = result >>> 1;
while (u + boundMinus1 - (result = u % bound) < 0L) {
u = random.nextLong() >>> 1;
}
result += randomNumberOrigin;
} else {
// range not representable as long
while (randomNumberOrigin >= result || result >= randomNumberBound) {
result = random.nextLong();
}
}
return result;
}
});
}
use of com.annimon.stream.function.LongSupplier in project Lightweight-Stream-API by aNNiMON.
the class GenerateTest method testStreamGenerate.
@Test
public void testStreamGenerate() {
LongStream stream = LongStream.generate(new LongSupplier() {
@Override
public long getAsLong() {
return 1234L;
}
});
assertThat(stream.limit(3), elements(arrayContaining(1234L, 1234L, 1234L)));
}
Aggregations