How it works...

In this recipe you learnt how to convert the elements of the stream using an intermediate operation and an expression that makes the conversion between the source and the destination types. We used three different methods in our example:

  • mapToDouble(): We used this method to convert Stream of objects into DoubleStream with double numbers as elements. This method receives as parameter a lambda expression or an implementation of the ToDoubleFunction interface. This expression receives an element of Stream and has to return a double value.
  • map(): We can use this method when we have to convert the elements of Stream to a different class. For example, in our case, we convert the Person class to a BasicPerson class. This method receives as parameter a lambda expression or an implementation of the Function interface. This expression must create the new object and initialize its attributes.
  • flatMap(): This method is useful in a more complex situation when you have to work with a Stream of Stream objects and you want to convert them to a unique Stream. This method receives as parameter a lambda expression or an implementation of the Function interface as the map() function, but in this case, this expression has to return a Stream object. The flatMap() method will automatically concatenate all those streams into a unique Stream.
..................Content has been hidden....................

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