title: Encapsulating Collection to Map transformation using Java 8's streams and collectors into a method
body: <p>I believe this question is not a duplicate despite the numerous questions about converting lists to maps in Java 8. Please bear with me.</p>
  
  <p>What I'm trying to do is gradually building a library of functions for myself to avoid having to repeat convoluted coded over and over involving streams and collectors, which tend to be much too verbose.</p>
  
  <p>At the moment I'm stuck in creating a method that transforms a collection into a map grouping by some field of the object of the collection.</p>
  
  <p>Let's say we have this class:</p>
  
  <pre><code>   class SomeClass {
        private String someField;
        private String anotherfield;
  
        public String getSomeField() {
           return someField;
        }
        public String getAnotherField() {
           return anotherfield;
        }
     }
  </code></pre>
  
  <p>And a list:</p>
  
  <pre><code>  List&lt;SomeClass&gt; myList = new ArrayList&lt;SomeClass&gt;();
    //populate the list...
  </code></pre>
  
  <p>And we want this, where each key of the map is a unique value for <code>someField</code> in the objects of the list:</p>
  
  <pre><code>Map&lt;String,List&lt;SomeClass&gt;&gt; myMap;
  </code></pre>
  
  <p>Which can be done like this:</p>
  
  <pre><code> Map&lt;String,List&lt;SomeClass&gt;&gt; myMap = 
      myList.stream().collect(Collectors.groupingBy(o -&gt; o.getSomeField()  ));
  </code></pre>
  
  <p>Here's the part that I can't solve. As I said I want to hide this into a cleaner method in a utility class that I intend to use in my projects. The method's signature:</p>
  
  <pre><code>   public static &lt;T, R&gt; Map&lt;R, List&lt;T&gt;&gt; collectionToMap(
        Collection&lt;T&gt; coll, Function&lt;? super T, ? extends R&gt; groupByKey)
  </code></pre>
  
  <p>Which would be called like:</p>
  
  <pre><code>Map&lt;String,List&lt;SomeClass&gt;&gt; amap = collectionToMap(myList, o -&gt; o.getSomeField());
  </code></pre>
  
  <p>Here is a clumsy attempt that doesn't compile, but just to give you an idea:</p>
  
  <pre><code>   public static &lt;T, R&gt; Map&lt;R, List&lt;T&gt;&gt; collectionToMap(Collection&lt;T&gt; coll, Function&lt;? super T, ? extends R&gt; groupByKey) {
        Map&lt;R,List&lt;T&gt;&gt; amap = coll.stream().collect(Collectors.groupingBy( 
              T::groupBy,
              Collectors.mapping(T, Collectors.toList())
              ));
        return amap;
     }
  </code></pre>
  
  <p>I can't wrap my head around it.</p>