39

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.

2 Answers 2

70

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Or .mapToObj(MyObject::new)
11
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.