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

前端 未结 5 1836
孤街浪徒
孤街浪徒 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:48

    Arrays.stream(int[]) creates an IntStream, not a Stream. So you need to call mapToObj instead of just map, when mapping an int to an object.

    This should work as expected:

    String commaSeparatedNumbers = Arrays.stream(numbers)
        .mapToObj(i -> ((Integer) i).toString()) //i is an int, not an Integer
        .collect(Collectors.joining(", "));
    

    which you can also write:

    String commaSeparatedNumbers = Arrays.stream(numbers)
        .mapToObj(Integer::toString)
        .collect(Collectors.joining(", "));
    

提交回复
热议问题