title: Java Streams: Grouping a List by two fields
body: <p>I have a list of cars</p>
  
  <p><code>List&lt;Car&gt; cars = ...;</code></p>
  
  <p>A car has an <code>Owner</code> and and <code>Owner</code> has a <code>ContactNumber</code></p>
  
  <p><strong>Car</strong></p>
  
  <pre><code>public class Car {
      private Owner owner;
      public Owner getOwner(){
         return owner;
      }
  }
  </code></pre>
  
  <p><strong>Owner</strong></p>
  
  <pre><code>public class Owner {
      private ContactNumber contactNumber;
      public ContactNumber getContactNumber() {
          return contactNumber;
      }
  }
  </code></pre>
  
  <p>I know I can group cars by Owners using</p>
  
  <pre><code>Map&lt;Owner, List&lt;Car&gt;&gt; groupByOwner = cars.stream().collect(groupingBy(Car::getOwner));
  </code></pre>
  
  <p>Is there a way I can then use streams to group by <code>Owner</code> and <code>ContactNumber</code> knowing that one <code>ContactNumber</code> can only ever be associated with one <code>Owner</code>?</p>
  
  <p>How would I also do this if a <code>ContactNumber</code> could be shared by multiple <code>Owner</code>s?</p>
  
  <p>i.e to create the below map:</p>
  
  <pre><code>Map&lt;Owner, List&lt;Car&gt;&gt; groupByOwner = cars.stream().collect(groupingBy(Car::getOwner))
  Map&lt;ContactNumber, Map&lt;Owner, List&lt;Car&gt;&gt;&gt; groupByContactNumberAndOwner = groupByOwner...
  </code></pre>