Cannot convert IntStream to some Object Stream

前端 未结 2 1054
萌比男神i
萌比男神i 2021-01-01 10:35

I\'m trying to use an IntStream to instantiate a stream of objects:

Stream myObjects = 
       IntStream
        .range(0, count         


        
相关标签:
2条回答
  • 2021-01-01 11:00

    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));
    
    0 讨论(0)
  • 2021-01-01 11:20
    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>

    0 讨论(0)
提交回复
热议问题