title: Group and calculate average of object array using stream in Java
body: <p>I have an array of PricingSamples objects :</p>
  
  <pre><code>public class PricingSample {
      private Date time;
      private Double average;
  
      public PricingSample(Date time, Double average) {
          this.time = time;
          this.average = average;
      }
  
      public Date getTime() {
          return time;
      }
  
      public void setTime(Date time) {
          this.time = time;
      }
  
      public Double getAverage() {
          return average;
      }
  
      public void setAverage(Double average) {
          this.average = average;
      }
  }
  </code></pre>
  
  <p>The samples are hourly for the past month. I would like to calculate the overall average for each day. I am able to count the number of occurencies in a stream and I am also able to count the sum of all the averages for each day, I just don't know how to combine those to things into one stream. </p>
  
  <p>Here is what I got to.</p>
  
  <p>Summing all averages for each day (I group by the substring of the Date property so it groups by day i.e. Thu Apr 26):</p>
  
  <pre><code> Map&lt;String, Double&gt; counts = Arrays.stream(samples).collect(Collectors.groupingBy((PricingSample e) -&gt; {
              return e.getTime().toString().substring(0, 10);
          },
              Collectors.summingDouble((PricingSample e) -&gt; {
                  return e.getAverage();
              })));
  </code></pre>
  
  <p>Getting the number of samples for each day:
  Map counts = </p>
  
  <pre><code>Arrays.stream(samples).collect(Collectors.groupingBy((PricingSample e) -&gt; {
              return e.getTime().toString().substring(0, 10);
          },
                  Collectors.counting()
              ));
  </code></pre>