Int stream and collect

Thus, it is difficult for me to understand the principle of this supplier, battery and adder in the collection from IntStream. I found an example.

IntStream.range(6,11)
         .collect(StringBuilder::new, 
                  StringBuilder::appendCodePoint,
                  StringBuilder::append);

Any mind explaining the part StringBuilder::appendCodePoint?

+4
source share
2 answers

Let wrap this thread to make from it byte[], and then Stringfrom the resulting array:

Arrays.toString(IntStream.range(6,11).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString().getBytes())

This will give us:

[6, 7, 8, 9, 10]

How does collection work?

He takes a stream 6..10and collects it in the following order:

  • It creates a new instance. StringBuilder
  • It accumulates , which adds a Unicode code point with help StringBuilder::appendCodePointto the battery. (equivalent: (StringBuilder sb, int x) -> sb.appendCodePoint(x))
  • , (2) StringBuilder, (1). (: (StringBuilder sb1, StringBuilder sb2) -> sb1.append(sb2))

collect() :

collect(Supplier<StrinBuilder> supplier,
                  ObjIntConsumer<StrinBuilder> accumulator,
                  BiConsumer<StrinBuilder, StrinBuilder> combiner);
+6

, :

IntStream.range(6, 11)
          .collect(StringBuilder::new, 
             (StringBuilder sb, int x) -> sb.appendCodePoint(x),  
             StringBuilder::append);

Consumer, Integer .

StringBuilder::appendCodePoint - , , .

+4

Source: https://habr.com/ru/post/1678733/


All Articles