title: Sorting by property in Java 8 stream
body: <p>Oh, those tricky Java 8 streams with lambdas. They are very powerful, yet the intricacies take a bit to wrap one's header around it all.</p>
  
  <p>Let's say I have a <code>User</code> type with a property <code>User.getName()</code>. Let's say I have a map of those users <code>Map&lt;String, User&gt;</code> associated with names (login usernames, for example). Let's further say I have an instance of a comparator <code>UserNameComparator.INSTANCE</code> to sort usernames (perhaps with fancy collators and such).</p>
  
  <p>So how do I get a list of the users in the map, sorted by username? I can ignore the map keys and do this:</p>
  
  <pre><code>return userMap.values()
      .stream()
      .sorted((u1, u2) -&gt; {
        return UserNameComparator.INSTANCE.compare(u1.getName(), u2.getName());
      })
      .collect(Collectors.toList());
  </code></pre>
  
  <p>But that line where I have to extract the name to use the <code>UserNameComparator.INSTANCE</code> seems like too much manual work. Is there any way I can simply supply <code>User::getName</code> as some mapping function, just for the sorting, and still get the <code>User</code> instances back in the collected list?</p>
  
  <p>Bonus: What if the thing I wanted to sort on were two levels deep, such as <code>User.getProfile().getUsername()</code>?</p>