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

前端 未结 5 1829
孤街浪徒
孤街浪徒 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 18:05

    No boxing, AFAIK, and no explosion of little strings added to the heap:

    public static void main(String[] args) {
        IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6);
        String s = stream.collect(StringBuilder::new, (builder, n) -> builder.append(',').append(n), (x, y) -> x.append(',').append(y)).substring(1);
        System.out.println(s);
    }
    

提交回复
热议问题