I don't feel the difference between map()
and mapToObj()
methods in Java 8 Streams. In both we can create and return objects to the streams, so why these methods exist as two, not only one.
Could you give me the explanation with examples?
You will see this cool pattern. The Stream
classes includes a IntStream
, LongStream
, DoubleStream
etc. This is so that you can use primitive types in stream operations. Because otherwise you have to use Stream<Integer>
or Stream<Double>
, which will box the values.
Similarly, the map
methods also do this. In the Stream<T>
class, there are mapToInt
, mapToDouble
methods, but the situation is a little bit different in the IntStream
, DoubleStream
classes.
In IntStream
, the map
method takes an IntUnaryOperator
, which maps an int to an int. If you want to map the stream to a Stream<T>
, you have to use mapToObj
. mapToObj
is a good name because it distinguishes from the map
that maps to ints. It signifies that the stream changes from a IntStream
to a Stream<T>
. The reason why mapToObj
is named like so is the same reason why mapToInt
is named like so - to signify a change in the Stream
type/