title: How exactly does the Java.reduce function with 3 parameters work?
body: <p>I am currently learning about the <code>java.reduce()</code>, and I recently came across something while reading up on some of the material and going through videos. I understand that there are 3 ways to use this, however, I am having issues getting the 3 parameter one to work. I was hoping that someone could better explain what is going on with it, and why I'm not getting the results I excepted (the average of a set of MagicNumber objects). Here is an example of what I have so far:</p>
  
  <p>An object, lets call it MagicNumber.java</p>
  
  <pre><code>public class MagicNumber{
      Random randomValueGenerator = new Random();
      int number;
      public MagicNumber(){
          this.number = randomValueGenerator.nextInt();
      }
  }
  </code></pre>
  
  <p>A random stream containing magic numbers</p>
  
  <pre><code>public static Stream&lt;MagicNumber&gt; getNStream(){
      List&lt;MagicNumber&gt; magic = new ArrayList&lt;MagicNumber&gt;();
      for(int i = 0; i &lt; 100; i++){
          magic.add(new MagicNumber());
      }
      return magic.stream();
  }
  </code></pre>
  
  <p>A function to return the average magic number</p>
  
  <pre><code>// This only returns the sum of the magic numbers and not the average
  public static double average(){
      Stream&lt;MagicNumbers&gt; magicNumberStream = getNStream();
      return magicNumberStream.reduce(
          0.0, // initial value
          (a,b) -&gt; a + (double)b.number,
          (a,b) -&gt; (a + b)/100
      )
  }
  </code></pre>
  
  <p>As the comment suggests, the above only returns the sum of all the magic numbers. While I expect something. So, I don't believe I fully understand the purpose of the 3rd parameter within the <code>reduce</code> function. Also, when I write something like the following using 2 parameters:
  A function to return the average magic number</p>
  
  <pre><code>// This throws an error due to the return type
  public static double average(){
      Stream&lt;MagicNumbers&gt; magicNumberStream = getNStream();
      return magicNumberStream.reduce(
          0.0, // initial value
          (a,b) -&gt; (double)(a.number + b.number)/100
      )
  }
  </code></pre>
  
  <p>I get the error <code>Bad return type in lambda expression: double cannot be converted to MagicNumber</code>. Could someone explain both (A) why these two <code>average</code> functions are not working as expected, and (B) how to modify them in order to get the result I'm looking for? I would really appreciate the help!</p>