title: Group a list inside an object by multiple attributes : Java 8
body: <p>How do I group a list inside an object by two of the object attributes?</p>
  
  <p>I'm using Drools 7.9.0 and Java 8. I have a <code>Result</code> class that is used as return to each matched Drools rule.</p>
  
  <pre><code>import lombok.Data;
  import lombok.NoArgsConstructor;
  
  import java.io.Serializable;
  import java.util.ArrayList;
  import java.util.List;
  
  @Data
  @NoArgsConstructor
  public class Result implements Serializable {
  
      private Integer id;
      private String name;
      private List&lt;Occurrences&gt; occurrences = new ArrayList&lt;&gt;();
  
      public void addOccurrence(Occurrences occurrence) {
          this.occurrences.add(occurrence);
      }
  }
  </code></pre>
  
  <p>After Drools execution, I end up with a <code>List&lt;Result&gt;</code>. Converted to JSON it looks like this.</p>
  
  <p><b>CURRENT OUTCOME:</b></p>
  
  <pre><code>[
       {
          name: "Whatever"
          id: 0001,
          occurrences: [{
             (...)
          }]
      },
      {
          name: "Whatever"
          id: 0001,
          occurrences: [{
             (...)
          }]
      },
      {
          name: "Whatever"
          id: 0002,
          occurrences: [{
             (...)
          }]
      },
      {
          name: "Other thing"
          id: 0002,
          occurrences: [{
             (...)
          }]
      }
  ]
  
  </code></pre>
  
  <p>I need to group up my list of <code>Result</code>s so the <code>ocurrences</code> are grouped by <code>id</code> and <code>name</code>, like this.</p>
  
  <p><b>EXPECTED OUTCOME:</b></p>
  
  <pre><code>[
      {
          name: "Whatever"
          id: 0001,
          occurrences: [{
             (...)
          }, {
             (...)
          }]
      },
      {
          name: "Whatever"
          id: 0002,
          occurrences: [{
             (...)
          }]
      },
      {
          name: "Other thing"
          id: 0002,
          occurrences: [{
             (...)
          }]
      }
  ]
  
  </code></pre>
  
  <p>What would be the best way to implement this? I have two options:</p>
  
  <ol>
  <li>Change Drools rules so my <code>List&lt;Result&gt;</code> is already structured the way I need. Maybe create a class with a <code>addResult</code> method that checks the list for <code>id</code> and <code>name</code> and add the occurrence to the right entry. But this is not ideal, because it will increase complexity inside the rules.</li>
  <li>Post-process my <code>List&lt;Result&gt;</code> so it groups the <code>occurrences</code> by <code>id</code> and <code>name</code>. But I have no idea how to do this in an optimized and simple way.</li>
  </ol>
  
  <p>What's the best way to do the 2nd option?</p>