title: How to use java8 stream operations to select only one element from each key in the map after grouping by two fields?
body: <p>I have a list of Person having multiple fields.</p>
  <p>I need to group by two of these fields. (age and name)</p>
  <p>So the result I get will be a map of map like:</p>
  <pre><code>Map&lt;Integer, Map&lt;String, List&lt;Person&gt;&gt; result;
  </code></pre>
  <p>now I need to remove the second key in the result, and also reduce the list to a single person. (which means I need to group all the persons by age, then have a list of Persons with different names for that same age.)The rules to select the persons of the same name are defined in a function like
  Person reduce(List persons){}
  Currently my code looks like this:</p>
  <pre><code>Map&lt;Integer, List&lt;Person&gt;&gt; select(List&lt;Person&gt; persons){
  
      Map&lt;Integer, Map&lt;string, List&lt;Person&gt;&gt; result = 
          persons
          .stream()
          .collect(groupingBy(p -&gt; p.getAge(),
                      groupingBy(p -&gt; p.getName(),
  toUnmodifiableList())   // HERE
                      // CAN WE REPLACE &quot;toUnmodifiableList()&quot; with something
                      //related to &quot;selectPerson&quot; method to simplify the flow?
                  )
          );
  
      return result
              .entrySet()
              .stream()
              .map(this::ignoreName)
              .collect(toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue))
  }
  
  
  Map.Entry&lt;Integer, List&lt;Person&gt;&gt; ignoreName(Map.Entry&lt;int, Map&lt;String, List&lt;Person&gt;&gt;&gt; persons){
      List&lt;Person&gt; ps = 
             persons
              .getValue()
              .values()
              .stream()
              .map(this::selectPerson)
              .collect(toUnmodifiableList());
      return AbstractMap.SimpleImmutableEntry&lt;&gt;(persons.getKey(), ps);
  }
  
  Person selectPerson(List&lt;Person&gt; persons){
      ///...
  }
  </code></pre>
  <p><strong>Now my question is, is there a way to simplify this? by doing something directly inside the downstream of groupingBy?</strong></p>
  <pre><code>Example:
  Person1: personID 1, age 24, name john
  Person2: personID 2, age 24, name anna
  Person3: personID 3, age 25, name mike
  Person4: PersonID 4, age 25, name mike 
  Person5: PersonID 5, age 25, name bob
  
  Map&lt;Integer, Map&lt;String, List&lt;Person&gt;&gt;&gt;:
  24 -&gt; john -&gt; personID 1
     -&gt; anna -&gt; personID 2
  25 -&gt; mike -&gt; personID 3
             -&gt; personID 4
     -&gt; bob  -&gt; personID 5
  Expected Result:
  Map&lt;Integer, List&lt;Person&gt;&gt;:
  24 -&gt; personID1
     -&gt; personID2
  25 -&gt; personID 3 or 4, depending on selectPerson logic
     -&gt; personID 5
  
  
  </code></pre>