Cannot convert IntStream to some Object Stream

2019-02-08 05:53发布

问题:

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.

回答1:

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));