I have never used streams in java before and am now trying to test how to accomplish simple examples with stream.
I want to return a random int int the range of 60-120 and have tried this:
return new Random().ints(1,60,121);
But I understand that I have to also convert it back to a int again but can't figure out how.
static IntStream. IntStream. of(int... values) Returns a sequential ordered stream whose elements are the specified values.
An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.
IntStream mapToDouble() in Java IntStream mapToDouble() returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.
IntStream range(int startInclusive, int endExclusive) returns a sequential ordered IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1. Parameters : IntStream : A sequence of primitive int-valued elements. startInclusive : The inclusive initial value.
IntStream range() method in Java The range() method in the IntStream class in Java is used to return a sequential ordered IntStream from startInclusive to endExclusive by an incremental step of 1. This includes the startInclusive as well.
Since you created a Stream with a single element, you can use findFirst()
to get that element:
int randInt = new Random().ints(1,60,121).findFirst().getAsInt();
That said, it doesn't make sense to create an IntStream
for the sake of producing a single random number. You can use Random
's nextInt()
instead.
If you want to generate multiple random integers, using an IntStream
would make more sense. In that case you can convert the generated IntStream
to an array:
int[] randInts = new Random().ints(1000,60,121).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With