title: Java lambda expressions, casting, and Comparators
body: <p>I was looking through Java source code for the <code>Map</code> interface and ran into this little snippet of code:</p>
  
  <pre><code>    /**
       * Returns a comparator that compares {@link Map.Entry} in natural order on value.
       *
       * &lt;p&gt;The returned comparator is serializable and throws {@link
       * NullPointerException} when comparing an entry with null values.
       *
       * @param &lt;K&gt; the type of the map keys
       * @param &lt;V&gt; the {@link Comparable} type of the map values
       * @return a comparator that compares {@link Map.Entry} in natural order on value.
       * @see Comparable
       * @since 1.8
       */
      public static &lt;K, V extends Comparable&lt;? super V&gt;&gt; Comparator&lt;Map.Entry&lt;K,V&gt;&gt; comparingByValue() {
          return (Comparator&lt;Map.Entry&lt;K, V&gt;&gt; &amp; Serializable)
              (c1, c2) -&gt; c1.getValue().compareTo(c2.getValue());
      }
  </code></pre>
  
  <p>From the method declaration I get that this is a generic method that returns a Comparator of a type that is either inferred from the map entries passed to it or explicitly provided in the method.</p>
  
  <p>What's really throwing me off is the return value. It appears that the lambda expression</p>
  
  <pre><code>(c1, c2) -&gt; c1.getValue().compareTo(c2.getValue());
  </code></pre>
  
  <p>is explicitly cast to a <code>Comparator&lt;Map.Entry&lt;K, V&gt;&gt;</code>. Is this right?</p>
  
  <p>I also noticed that the apparent cast includes <code>&amp; Serializable</code>. I've never seen an interface combined with a class in a cast before, but it looks like the following valid in the compiler:</p>
  
  <p><code>((SubClass &amp; AnInterface) anObject).interfaceMethod();</code></p>
  
  <p>Although the following doesn't work:</p>
  
  <pre><code>public class Foo {
      public static void main(String[] args) {
          Object o = new Foo() {
              public void bar() {
                  System.out.println("nope");
              }
          };
          ((Foo &amp; Bar) o).bar();
      }   
  }
  
  interface Bar {
      public void bar();
  }
  </code></pre>
  
  <p>So, two questions:</p>
  
  <ol>
  <li><p>How does adding an interface to a cast supposed to work? Does this just enforce the return type of an interface's method?</p></li>
  <li><p>Can you cast a Lambda expression to a <code>Comparator</code>? What else can they be cast as? Or is a lambda expression essentially just a <code>Comparator</code>? Can someone clarify all of this?</p></li>
  </ol>