Primitive streams

Primitive streams were introduced in Java 8, to take advantage of primitive data types in Java while using Streams (again, Streams are basically from Java, and Kotlin just adds a few extension functions to the Streams API). IntStream, LongStream, and DoubleStream are part of those primitive Streams.

These primitive streams work similarly to the normal Stream with some added features of the primitive data types.

So, let's take an example; have a look at the following program:

  fun main(args: Array<String>) { 
      val intStream = IntStream.range(1,10) 
      val result = intStream.sum() 
      println("The sum of elements is $result") 
  } 

So, we created an IntStream value with the IntStream.range() function, the range function takes two integers as the starting and ending point and creates a Stream ranging from the specified integers, with both included. We then calculated the sum and printed it. The program seems quite easy, and credit goes to IntStream obviously, why? Think of calculating the sum of elements with that ease; without IntStream, we would have to loop through all the elements to calculate the sum.

The following is another example of primitive streams:

  fun main(args: Array<String>) { 
      val doubleStream = DoubleStream.iterate(1.5,{item ->     item*1.3})//(1) 
      val avg = doubleStream 
              .limit(10)//(2) 
              .peek { 
                  println("Item $it") 
              }.average()//(3) 
      println("Average of 10 Items $avg") 
  } 

Have a look at the following output before we explain the program:

So, let's explain the program:

  • On comment (1), we created a DoubleStream value with the factory method iterate(). The iterate method takes a double as the seed of the Stream, and an operand, which will be iteratively applied to generate the elements of the Stream, for example if you pass x as the seed and f as the operator, the Stream will return x as the first element, f(x) as the second element, f(f(x)) as the third element, and so on. This function creates a Stream of infinite size.
  • We used the limit operator at comment (2), as we wanted only 10 elements from that stream, not all the elements till infinity. On comment (3), we calculated average.

So, let's have a look at the different ways to create a Stream.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.249.42