I'm trying to use an IntStream
to instantiate a stream of objects:
Stream<MyObject> myObjects =
IntStream
.range(0, count)
.map(id -> new MyObject(id));
But it says that it cannot convert MyObject
to int
.
What is the difference between both? IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.
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 rangeClosed() method in Java The rangeClosed() class in the IntStream class returns a sequential ordered IntStream from startInclusive to endInclusive by an incremental step of 1. This includes both the startInclusive and endInclusive values.
The IntStream
class's map
method maps int
s to more int
s, with a IntUnaryOperator
(int
to int
), not to objects.
Generally, all streams' map
method maps the type of the stream to itself, and mapToXyz
maps to a different type.
Try the mapToObj
method instead, which takes an IntFunction
(int
to object) instead.
.mapToObj(id -> new MyObject(id));
Stream stream2 = intStream.mapToObj( i -> new ClassName(i));
This will convert the intstream
to Stream
of specified object type, mapToObj
accepts a function.
There is method intStream.boxed()
to convert intStream directly to Stream<Integer>
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