title: Java Collectors grouping-by dynamic fields
body: <p>I have the following nested groupingBy block:</p>
  
  <pre><code>Map&lt;String,Map&lt;String,Long&gt;&gt; namesCountersMap =
              events.stream().collect(
                  Collectors.groupingBy(
                      namesDAO::getName,
                      Collectors.groupingBy(
                          genericDAO::SOME_DYNAMIC_FIELD,
                          Collectors.counting())
                  )
              );
  </code></pre>
  
  <p>There is a situation where I need to call this block 3 times, and the only thing I change is the inner groupingBy field ("SOME_DYNAMIC_FIELD").</p>
  
  <p>Basically what i'm trying to do, is to use group-by and counting for a different field (at the second level) every time, and then merge the results.</p>
  
  <p>Example:</p>
  
  <pre><code>{
        "NamesRecords": {
          "Sam": {
              "Cars": 4
              "Bags": 6 
              "Houses": 2 
          },
  
          "Bob": {
              "Cars": 2
              "Bags": 1 
              "Houses": 3 
          },
  
        }
  }
  </code></pre>
  
  <p>As you can see, group-by at the 2nd level is done by 3 different fields, that's is why I need to duplicate this block of code three times.</p>
  
  <p>If I pass a parameter of fieldToGroupBy to the function, is there a way I can use it dynamically? Or if you have any other ideas of how to avoid code duplication, I would love to hear.</p>