Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IntStream to int

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.

like image 571
Burton Avatar asked Feb 07 '18 08:02

Burton


People also ask

What does IntStream return?

static IntStream. IntStream. of(int... values) Returns a sequential ordered stream whose elements are the specified values.

What is an IntStream?

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.

How do I convert IntStream to DoubleStream?

IntStream mapToDouble() in Java IntStream mapToDouble() returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.

How does IntStream range () work?

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.

What is IntStream range in java?

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.


1 Answers

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();
like image 132
Eran Avatar answered Oct 23 '22 09:10

Eran