Java 8 stream groupingBy: summing an attributeValue
<p>I have a simple class Foo:</p>

<pre><code>class Foo {
   String type; 
   Integer quantity;
   String code;
   //...
}
</code></pre>

<p>and a list of objects of that type:</p>

<pre><code>{ type=11, quantity=1, code=A },
{ type=11, quantity=2, code=A },
{ type=11, quantity=1, code=B },
{ type=11, quantity=3, code=C },
{ type=12, quantity=2, code=A },
{ type=12, quantity=1, code=B },
{ type=11, quantity=1, code=B },
{ type=13, quantity=1, code=C },
{ type=13, quantity=3, code=C }
</code></pre>

<p>I need to first group by type, and I can do that:</p>

<pre><code>Map&lt;String, List&lt;Foo&gt;&gt; typeGroups = mylist.stream().collect(Collectors.groupingBy(Foo::getType));
</code></pre>

<p>The next step would be transforming that <code>Map</code> to a <code>List&lt;Foo&gt;</code> like this:</p>

<pre><code>{ type=11, quantity=3, code=A },
{ type=11, quantity=2, code=B },
{ type=11, quantity=3, code=C },
{ type=12, quantity=2, code=A },
{ type=12, quantity=1, code=B },
{ type=13, quantity=4, code=C }
</code></pre>

<p>In SQL, I'd have this kind of query: </p>

<pre><code>SELECT type, code, SUM(quantity) FROM Foo GROUP BY type, code
</code></pre>

<p>Let me explain in plain english, too.</p>

<p>I need to end up with a List of Foos. Each one's code must be unique among its group, and quantity must be the aggregate sum of Foos having same code among their group.</p>

<p>I tried doing that using <code>groupingBy()</code> with <code>summingInt()</code> but can't get the desired result.</p>