title: Cast the return type of a lambda expression and sort a list with a custom comparator
body: <p>I have a <a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/tree/DefaultMutableTreeNode.html" rel="nofollow"><code>List&lt;DefaultMutableTreeNode&gt;</code></a> and want to sort the list by a property of the <a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/tree/DefaultMutableTreeNode.html#getUserObject--" rel="nofollow"><code>userObject</code></a> with a custom comparator. </p>
  
  <p>In order to provide a simple example I will use the user object <code>Person</code></p>
  
  <pre><code>public class Person {
      private String firstname;
      private String lastname;
  
      public Person(String firstname, String lastname) {
          this.firstname = firstname;
          this.lastname = lastname;
      }
  
      public String getFirstname() {
          return firstname;
      }
  
      public String getLastname() {
          return lastname;
      }
  
  }
  </code></pre>
  
  <p>and a custom comparator</p>
  
  <pre><code>public class PersonComparator implements Comparator&lt;Person&gt; {
  
      @Override
      public int compare(Person o1, Person o2) {
          // to keep the example simple I just compare the firstnames here
          return o1.getFirstname().compareTo(o2.getFirstname());
      }
  
  }
  </code></pre>
  
  <p>My first thought was to use <code>Comparator.comparing</code> with a method reference as key extractor and a key comparator.</p>
  
  <pre><code>public static void main(String[] args) {
      List&lt;DefaultMutableTreeNode&gt; nodes = new ArrayList&lt;DefaultMutableTreeNode&gt;();
  
      nodes.add(new DefaultMutableTreeNode(new Person("James", "Smith")));
      nodes.add(new DefaultMutableTreeNode(new Person("Paul", "Clark")));
      nodes.add(new DefaultMutableTreeNode(new Person("Anthony", "Brown")));
  
      Comparator&lt;Person&gt; myComparator = new PersonComparator();
      nodes.sort(Comparator.comparing(DefaultMutableTreeNode::getUserObject, myComparator));
  
  }
  </code></pre>
  
  <p>But this gives me (of course) a compiler error since the <code>DefaultMutableTreeNode.getUserObject()</code> returns an <code>Object</code> and not a <code>Person</code>.</p>
  
  <p>How can I cast the retrun type of the lambda method reference <code>DefaultMutableTreeNode::getUserObject</code>?</p>
  
  <p>Or do you have any other options? </p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I can do it this way, but is there an easier way? (in one line)</p>
  
  <pre><code>Function&lt;DefaultMutableTreeNode, Object&gt; userObject = DefaultMutableTreeNode::getUserObject;
  nodes.sort(Comparator.comparing(userObject.andThen(Person.class::cast), myComparator));
  </code></pre>