Search code examples
javajava-8java-stream

Where is the terminal operation IntStream.sum() implemented in Java 8?


I see that the method sum is defined in interface IntStream. When you write IntStream.range(0, 200).sum(), how is the implementation called? Where is it? I couldn't find it.


Solution

  • As for every interface, it's defined in the concrete class(es) that implement the interface.

    In this case, it's in java.util.stream.IntPipeline, which is not a public class. But you shouldn't care about that. All you need to know is that an IntStream has that method, which does what the javadoc of the method does.

    If you're really curious about its implementation, look in the source code of IntPipeline.java:

    return reduce(0, Integer::sum);
    

    Note on how I found out extremely easily: I just open the type hierarchy of IntStream in my IDE (IntelliJ, but all decent IDEs have that functionality), and notice that it has a single direct implementation: IntPipeline, which indeed contains the method.