Why can't I map integers to strings when streaming from an array?

前端 未结 5 1830
孤街浪徒
孤街浪徒 2020-12-04 17:00

This code works (taken in the Javadoc):

List numbers = Arrays.asList(1, 2, 3, 4);
String commaSeparatedNumbers = numbers.stream()
    .map(i -         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 17:47

    Arrays.stream(numbers) creates an IntStream under the hood and the map operation on an IntStream requires an IntUnaryOperator (i.e a function int -> int). The mapping function you want to apply does not respect this contract and hence the compilation error.

    You would need to call boxed() before in order to get a Stream (this is what Arrays.asList(...).stream() returns). Then just call map as you did in the first snippet.

    Note that if you need boxed() followed by map you probably want to use mapToObj directly.

    The advantage is that mapToObj doesn't require to box each int value to an Integer object; depending on the mapping function you apply of course; so I would go with this option which is also shorter to write.

提交回复
热议问题