Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert IntStream to some Object Stream

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.

like image 343
hba Avatar asked Jan 27 '16 20:01

hba


People also ask

What is the difference between Stream and IntStream?

What is the difference between both? IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.

What is IntStream in Java?

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.

What is IntStream rangeClosed?

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.


2 Answers

The IntStream class's map method maps ints to more ints, 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));
like image 145
rgettman Avatar answered Oct 25 '22 08:10

rgettman


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>

like image 24
sreerag Avatar answered Oct 25 '22 09:10

sreerag