title: Java 8 - How to sum all List element in a Map of Lists
body: <p>I have a Map of Lists of a particular Object and I want to add all the elements of the lists based on a particular instance variable.</p>
  
  <p>My Object:</p>
  
  <pre><code>class Risk{ 
      Integer id, riskValue, totRisk=0;
      String name;
  
      Integer getId(){
         return id;
      }
      Risk(Object[] result){
           id=(Integer)result[0];
           riskValue=(Integer)result[1];
           name=(String)result[3];
      }
  }
  </code></pre>
  
  <p>I get from the Database a List of Arrays of type object: </p>
  
  <pre><code>List&lt; Object[] &gt; results=getResults();
  </code></pre>
  
  <p>I use Java 8 to group my Data by ID, because I want to <strong>SUM</strong> by <code>riskValue</code> all the objects of type <code>Risk</code> having the same <code>id</code>. </p>
  
  <p>This is what I do:</p>
  
  <pre><code>List&lt;Risk&gt; risks=results.stream().map(Risk::new).collect(Collectors.toList());
  Map&lt;Integer, List&lt;Risk&gt;&gt; byId=risks.stream.collect(Collectors.groupingBy(Risk::getId));
  </code></pre>
  
  <p>At this point I have all my Risk objects grouped by ID. And I want for each list to sum all the objects by <code>riskValue</code> and have the total in the variable <code>totRisk</code> </p>
  
  <p>How to compute in the variable <code>totRisk</code> the total of the variables <code>riskValue</code> in each List?</p>
  
  <p>Note1: <strong>I want to do it using Java 8, I know how to do it using Java 7 and below.</strong> </p>
  
  <p>Note2: Perhaps it's also possible to do it in one go, by not having first to group by ID. What I want to achieve is to sum all the objects with the same ID in the original <code>List&lt;Object[]&gt; results</code>. If it can be done with only one statement is even better.</p>