<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Java 8.0</title>
	<atom:link href="http://www.javabeat.net/category/java-8-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Enhanced Collections API in Java 8- Supports Lambda expressions</title>
		<link>http://www.javabeat.net/2012/05/enhanced-collections-api-in-java-8-supports-lambda-expressions/</link>
		<comments>http://www.javabeat.net/2012/05/enhanced-collections-api-in-java-8-supports-lambda-expressions/#comments</comments>
		<pubDate>Sat, 26 May 2012 14:50:34 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3996</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Continuing with our exploration of JSR-335 lets look at some of the enhancements to the collections API as part of the Project Lambda effort. A new feature in the language and not supported by the existing API is just not what the programmers would want. And this is what Brian Goetz and his team working [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>Continuing with our exploration of JSR-335 lets look at some of the enhancements to the collections API as part of the Project Lambda effort. A new feature in the language and not supported by the existing API is just not what the programmers would want. And this is what Brian Goetz and his team working on JSR-335 realized. It was not an easy task of enhancing the existing API without breaking uncountable lines of code. That was a challenge which they took up and managed to get around this by introducing the concept of <a href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/" title="Virtual Extension (or Defender) Methods in Java 8">defender methods</a>. </p>
<p>To outline the major changes in collection API:</p>
<ul>
<li>Support for internal iteration by providing methods like forEach, filter, map and others which are added to the Iterable interface with default implementations (<a href="http://www.javabeat.net/2012/05/use-of-virtual-extension-methods-in-the-java-8-apis/" title="Use of Virtual Extension methods in the Java 8 APIs">Defender methods</a>).</li>
<li>Explicit parallel APIs for greater parallelism support. These can be combined with Fork/Join to divide the tasks</li>
<li>Greater stress on immutability and avoiding in-place mutation which was done in the conventional for-each loops</li>
</ul>
<p>All of these are possible by giving the API/method power to decide its iteration. And the caller would pass in a block of code which would be applied on each of the element or elements decided by the API/method being invoked. That&#8217;s pretty much of the theory, lets see it in action on a List of integers from 1 to 10.</p>
<pre class="brush: java; title: ; notranslate">
List&lt;Integer&gt; counts = new ArrayList&lt;Integer&gt;();
for(int i=1;i &lt;= 10; i++){
  counts.add(i);
}
</pre>
<p>Iterating through the elements in the list:</p>
<pre class="brush: java; title: ; notranslate">
//Using external iterators
System.out.println(&quot;Using external iterator&quot;);
for(Integer i : counts){
  System.out.print(i+&quot; &quot;);
}
System.out.println();
</pre>
<p>versus</p>
<pre class="brush: java; title: ; notranslate">
//Using internal iterators
System.out.println(&quot;Using internal iterator&quot;);
//Passing a code block to forEach method
counts.forEach(i -&gt; {System.out.print(i*2+&quot; &quot;);});
System.out.println();
</pre>
<p>Very concise right? Digging into forEach method introduced in Iterable interface, it is implemented as:</p>
<pre class="brush: java; title: ; notranslate">
void forEach(Block&lt;? super T&gt; block) default {
  Iterables.forEach(this, block);
}
</pre>
<p>if you are confused about the use of &#8220;default&#8221; keyword, then please read about it <a href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/" title="Virtual Extension (or Defender) Methods in Java 8">here</a>. Iterables is a new class to be introduced in Java 8 and the forEach method in Iterables expects an collection/something which can be iterated and the block of code to apply on the each element iterated, the implementation is:</p>
<pre class="brush: java; title: ; notranslate">
public static &lt;T&gt; Iterable&lt;T&gt; 
   forEach(final Iterable&lt;? extends T&gt; iterable,
           final Block&lt;? super T&gt; block) {
  Objects.requireNonNull(iterable);
  Objects.requireNonNull(block);
  for (T each : iterable) {
    block.apply(each);
  }

  return (Iterable&lt;T&gt;) iterable;
}
</pre>
<p>Looks like forEach method does nothing different from the older for-each loop, that&#8217;s how forEach ought to work. If you want to maintain immutability you can use a different method which I will write a little later. But for now, forEach iterates through the iterable and applies the block to each of the element. Going into the Block and apply method would be out of scope of this article, lets look at it in a different article. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets explore a bit further and print all the even elements of the list.<br />
Using external iteration ( for-each loop) we would have</p>
<pre class="brush: java; title: ; notranslate">
for ( Integer i : counts){
  if ( i % 2 == 0 ){
    System.out.print(i+&quot; &quot;);
  }
}
</pre>
<p>and using the new APIs:</p>
<pre class="brush: java; title: ; notranslate">
//filter evaluates the block
//and returns a new iterable.
counts.filter(i -&gt; i%2 == 0)
      .forEach(i-&gt; {System.out.print(i+&quot; &quot;);});
</pre>
<p>the filter method doesn&#8217;t create a new collection instead it creates a new Iterable. The difference it makes is that there is no intermediate collection created after filter is invoked. </p>
<p>Another example before we close- lets multiply all the odd elements by 2 and create a new list.<br />
Using the for-each loop, this can be done as:</p>
<pre class="brush: java; title: ; notranslate">
List&lt;Integer&gt; newCounts = new ArrayList&lt;Integer&gt;();
for(Integer i : counts){
  if ( i % 2 != 0 ){
      newCounts.add(i*2);
  }
}
for(Integer i : newCounts){
System.out.print(i+&quot; &quot;);
}
</pre>
<p>and the same using new API:</p>
<pre class="brush: java; title: ; notranslate">
List&lt;Integer&gt; newCountsNew = new ArrayList&lt;Integer&gt;();
counts.filter(i -&gt; i % 2 != 0)
      .map(i -&gt; i*2)
      .into(newCountsNew);
newCountsNew.forEach(i -&gt; {System.out.print(i+&quot; &quot;);});
</pre>
<p>Apart from the other benefits mentioned at the beginning the above code which uses new APIs is more readable than the one which uses for-each. </p>
<p>If you want to read more about the state of the APIs with respect to the lambda expressions, please do so <a href="http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html" title="State of Lambda" target="_blank">here</a>.<br />
The examples used above can be found <a href="https://gist.github.com/2794193" target="_blank">here</a> as well.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-8-0%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-8-0/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-8-0/feed/" data-count="vertical" data-text="Java 8.0" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/enhanced-collections-api-in-java-8-supports-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>A sneak peak at the Lambda Expressions in Java 8</title>
		<link>http://www.javabeat.net/2012/05/a-sneak-peak-at-the-lambda-expressions-in-java-8/</link>
		<comments>http://www.javabeat.net/2012/05/a-sneak-peak-at-the-lambda-expressions-in-java-8/#comments</comments>
		<pubDate>Mon, 21 May 2012 20:18:04 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3856</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Mike Duigou announced here that the Iteration 1 of Lambda Libraries is complete which includes support for defender methods, enhancement of the collection apis among other changes. Before proceeding further its good to read about Functional Interfaces and Defender Methods to some extent. Lets dive into an example, consider sorting of Person objects where each [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Mike Duigou announced <a title="Project Lambda" href="http://mail.openjdk.java.net/pipermail/lambda-dev/2012-May/004861.html" target="_blank">here</a> that the Iteration 1 of Lambda Libraries is complete which includes support for <a title="Virtual Extension (or Defender) Methods in Java 8" href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/" target="_blank">defender methods</a>, enhancement of the collection apis among other changes.</p>
<p>Before proceeding further its good to read about <a title="What are Functional Interfaces and Functional Descriptor?" href="http://www.javabeat.net/2012/05/what-are-functional-interfaces-and-functional-descriptor/">Functional Interfaces</a> and <a title="Virtual Extension (or Defender) Methods in Java 8" href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/">Defender Methods</a> to some extent.</p>
<p>Lets dive into an example, consider sorting of Person objects where each Person would have firstName, lastName, dateOfBirth, placeOfBirth</p>
<pre class="brush: java; title: ; notranslate">
class Person {

  public Person(String fName,
                String lName,
                Date dob,
                String place)
  {
    firstName = fName;
    lastName = lName;
    dateOfBirth = dob;
    placeOfBirth = place;
  }

  @Override
  public String toString(){
    return firstName+&quot; &quot;+lastName;

  }
  String firstName;
  String lastName;
  Date dateOfBirth;
  String placeOfBirth;
}
</pre>
<p>Lets see how we can sort this with and without using lambda expressions</p>
<pre class="brush: java; title: ; notranslate">
public class LambdaBasicDemo {

  public static void main(String[] args) {
    List&lt;Person&gt; people = createPeople();

    // Sorting pre Lambda Expression era
    //Sorting by firstName
    Collections.sort(people,new Comparator&lt;Person&gt;() {
      @Override
      public int compare(Person o1, Person o2) {
        return o1.firstName.compareTo(o2.firstName);
      }
    });
    System.out.println(&quot;Firstname sort: &quot;+people);

    //Sorting using Lambda expressions and updated collection API
    //Sorting by lastName
    people.sort((o1,o2) -&gt; {
      return o1.lastName.compareTo(o2.lastName);
    });
    System.out.println(&quot;Lastname sort:&quot; +people);

  }

  static List&lt;Person&gt; createPeople(){
    Calendar calendar = Calendar.getInstance();
    calendar.set(1900, Calendar.JANUARY,01,12,00);
    List&lt;Person&gt; people = new ArrayList&lt;&gt;();
    Person person = new Person(&quot;Raju&quot;,&quot;Sarkar&quot;,calendar.getTime(),&quot;Delhi&quot;);
    people.add(person);

    calendar.set(1950,Calendar.JUNE,30,12,30);
    person = new Person(&quot;Anant&quot;,&quot;Patil&quot;, calendar.getTime(),&quot;Pune&quot;);
    people.add(person);

    calendar.set(1950,Calendar.DECEMBER,30,12,30);
    person = new Person(&quot;Danny&quot;,&quot;Great&quot;, calendar.getTime(),&quot;London&quot;);
    people.add(person);

    return people;
  }
}
</pre>
<p>The output would be:</p>
<pre class="brush: bash; title: ; notranslate">
Firstname sort: [Anant Patil, Danny Great, Raju Sarkar]
Lastname sort:[Danny Great, Anant Patil, Raju Sarkar]
</pre>
<p>You all are aware of how the collections are sorted using the Collection API and Comparator so I am not going into that. There&#8217;s an interesting syntax which uses a dash(-) and an greater than symbol(&gt;) [dash-rocket], lets look into a bit of detail about this syntax:</p>
<pre class="brush: java; title: ; notranslate">
//Sorting using Lambda expressions and updated collection API
//Sorting by lastName
people.sort((o1,o2) -&gt; {
  return o1.lastName.compareTo(o2.lastName);
});
</pre>
<p>There obvious difference between the verbosity of the code for sorting by creating anonymous inner class and by using Lambda expressions. The Lambda expression consists of lambda parameters and Lambda body. A Lambda expression is represented as () -&gt; {} where () contains the lambda parameters and the {} contains the lambda body. A lambda expression can be void returning or value returning i.e can return nothing or return result of some expression.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>In the above example, we are constructing a lambda expression for the <a title="What are Functional Interfaces and Functional Descriptor?" href="http://www.javabeat.net/2012/05/what-are-functional-interfaces-and-functional-descriptor/">functional interface</a> Comparator with a functional descriptor (T o1, T o2) -&gt; int.</p>
<p>Note: Something interesting to note here is that with Java 8 the Comparator interface has 2 more methods</p>
<pre class="brush: java; title: ; notranslate">
Comparator&lt;T&gt; reverse() default {
  return Collections.reverseOrder(this);
}
Comparator&lt;T&gt; compose(Comparator&lt;? super T&gt; other) default {
  return Comparators.compose(this, other);
}
</pre>
<p>We would like to keep this confusion aside for time being and I will get back on this and explain as to why and how the defender methods are not considered. If someone if aware of the reason, please add them as comments.</p>
<p>Digging deeper into the lambda expression, the <code>(o1, o2)</code> indicates the lambda parameters. The type information for o1 and o2 are inferred from the context in which it is being used, and in our case they are of type Person. The <code>{return o1.lastName.compareTo(o2.lastName);}</code> is the lambda body.</p>
<p>Advantages of using Lambda expressions over Anonymous inner class approach:</p>
<ul>
<li>Lambda expressions are lighter on code than the anonymous inner classes.</li>
<li>An advantage of using Lambda expressions is the resolution of <strong>this</strong> and <strong>super</strong> when used within the Lambda expression. In case of anonymous inner class approach the <strong>this</strong> and <strong>super</strong> are resolved to the anonymous inner class. And this is not at all useful because there&#8217;s nothing that one would want from the anonymous inner class. But in case of lambda expressions these resolve to the enclosing class.</li>
<li>Permissibility of use of effectively final variables in lambda expressions, where as only final variables can be used in local inner classes</li>
</ul>
<p>Interestingly, compiling LambdaBasicDemo.java gives 3 class files (apart from Person.class): LambdaBasicDemo.class, LambdaBasicDemo$1.class, LambdaBasicDemo$2.class.</p>
<ul>
<li>LambdaBasicDemo.class corresponds to the public class LambdaBasicDemo.</li>
<li>LambdaBasicDemo$1.class corresponds to the anonymous inner class for Comparator</li>
<li>and LambdaBasicDemo$2.class corresponds to the lambda expression. So under the hood, the compiler wraps this lambda expression with a new class and then instantiates the same.</li>
</ul>
<p>That&#8217;s pretty much it for a sneak peak. Stay tuned for lot more as I continue to explore the feature.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/a-sneak-peak-at-the-lambda-expressions-in-java-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What are Functional Interfaces and Functional Descriptor?</title>
		<link>http://www.javabeat.net/2012/05/what-are-functional-interfaces-and-functional-descriptor/</link>
		<comments>http://www.javabeat.net/2012/05/what-are-functional-interfaces-and-functional-descriptor/#comments</comments>
		<pubDate>Sun, 20 May 2012 16:17:24 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3883</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>There is no Java developer who is not familiar with these Interfaces which contain only one method. If you are not familiar, no worries I will in the course of this article throw some light on such interfaces. Those who have created GUI applications using Swing/AWT would be familiar with ActionListener interface, those working on [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>There is no Java developer who is not familiar with these Interfaces which contain only one method. If you are not familiar, no worries I will in the course of this article throw some light on such interfaces.</p>
<p>Those who have created GUI applications using Swing/AWT would be familiar with ActionListener interface, those working on mutli threaded applications or concurrent applications would be familiar with Runnable, Callable, Executor and other interfaces. Those who worked on sorting of objects would be familiar Comparator interface. What is it that is common between them? Yes, you got it right, they are interfaces with one method (not considering the methods it inherits from the Object class). These were called Single Abstract Method classes, its were because with Java 8 these are called as Functional Interfaces.</p>
<p>Runnable:</p>
<pre class="brush: java; title: ; notranslate">
public interface Runnable {
    public abstract void run();
}
</pre>
<p>Callable:</p>
<pre class="brush: java; title: ; notranslate">
public interface Callable&lt;V&gt; {
    V call() throws Exception;
}
</pre>
<p>Executor:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
public interface Executor {
    void execute(Runnable command);
}
</pre>
<p>Functional Interfaces can also have abstract methods which are inherited from Super interfaces and those should be override equivalent (read more about override equivalent methods <a title="Override Equivalent" href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.2" target="_blank">here</a>). For example:</p>
<pre class="brush: java; title: ; notranslate">
interface I1{
  void method1(List&lt;Number&gt; n);
}
interface I2{
  void method1(List n);
}
interface I3 extends I1, I2{} // Valid Functional Interface.
interface I4{
  int method1(List n);
}
interface I5 extends I2,I4{} //Not a functional interface
</pre>
<p>The bottom line is that functional interfaces are those that have single abstract methods (apart from the inherited public methods from Object class). The single method might not be the only method, but can be inherited from multiple interfaces but they signatures are equivalent to each other (See <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.2" target="_blank">Override equivalent</a>) such that those multiple methods actually represent/act as a single method.</p>
<p>Along with the functional interfaces, there&#8217;s a concept called functional descriptors associated. Functional descriptor of an Interface is the method type of the single abstract method of the interface. Here the method type of a method includes: argument types, return type and the throws clause.<br />
In our above examples the functional descriptors are</p>
<pre class="brush: java; title: ; notranslate">
//For Runnable
() -&gt; void
//For Executor
(Runnable) -&gt; void
//For Interface I3
(List&lt;String&gt;) -&gt; void
</pre>
<p>These concepts are used while constructing lambda expressions and using them. Just to give a brief: all these functional interfaces can be represented by using Lambda expressions, the compiler in turn infers the context in which the lambda expression is used and uses the corresponding Functional Interface.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/what-are-functional-interfaces-and-functional-descriptor/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Use of Virtual Extension methods in the Java 8 APIs</title>
		<link>http://www.javabeat.net/2012/05/use-of-virtual-extension-methods-in-the-java-8-apis/</link>
		<comments>http://www.javabeat.net/2012/05/use-of-virtual-extension-methods-in-the-java-8-apis/#comments</comments>
		<pubDate>Fri, 18 May 2012 06:00:08 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3733</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In wrote a bit about Virtual extension methods here and here. I thought of going over this implementation in the JDK, so that it will give us an idea of how these can be applied. As I told earlier, the main intention of adding the virtual extension methods was to provide an option to extend [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In wrote a bit about Virtual extension methods <a href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/" title="Virtual Extension (or Defender) Methods in Java 8">here</a> and <a href="http://www.javabeat.net/2012/05/resolution-of-the-invocation-of-virtual-extension-methods-in-java-8/" title="Resolution of the invocation of Virtual Extension Methods in Java 8">here</a>. I thought of going over this implementation in the JDK, so that it will give us an idea of how these can be applied. </p>
<p>As I told <a href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/" title="Virtual Extension (or Defender) Methods in Java 8">earlier</a>, the main intention of adding the virtual extension methods was to provide an option to extend the existing interfaces (by adding new methods) without breaking the existing usages. Consequently the main contender for this is the Collection interface in java.util package. All the collection classes in Java implement this interface. Few methods were added to the Collection interface to provide support for the new collections API. </p>
<p>Lets consider the retainAll method as defined below (copied as is from the source distributed with the JDK):</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
/**
 * Retains all of the elements of this collection which 
 * match the provided predicate.
 *
 * @param filter a predicate which returns {@code true} 
 * for elements to beretained.
 * @return {@code true} if any elements were retained.
 */
// XXX potential source incompatibility with retainAll(null)
// now being ambiguous
boolean retainAll(Predicate&lt;? super E&gt; filter) default {
    return CollectionHelpers.retainAll(this, filter);
}
</pre>
<p>New CollectionHelpers class is introduced which contains the implementation of various methods used as virtual extension methods. Also notice that the method in the Collection interface doesn&#8217;t have any code/implementation details, instead they refer to methods from another class (CollectionHelpers in this case). </p>
<p>The CollectionHelpers.retainApp is defined as (From the source for CollectionHelpers):</p>
<pre class="brush: java; title: ; notranslate">
public static &lt;E&gt; boolean retainAll(Collection&lt;E&gt; collection, 
                                    Predicate&lt;? super E&gt; filter ) {
  boolean retained = false;
  Iterator&lt;E&gt; each = collection.iterator();
  while(each.hasNext()) {
    if(!filter.test(each.next())) {
      each.remove();
    } else {
      retained = true;
    }
   }
  return retained;
}
</pre>
<p>There are numerous such examples in the JDK 8, and one can explore different options from the source for the Java APIs. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/use-of-virtual-extension-methods-in-the-java-8-apis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Resolution of the invocation of Virtual Extension Methods in Java 8</title>
		<link>http://www.javabeat.net/2012/05/resolution-of-the-invocation-of-virtual-extension-methods-in-java-8/</link>
		<comments>http://www.javabeat.net/2012/05/resolution-of-the-invocation-of-virtual-extension-methods-in-java-8/#comments</comments>
		<pubDate>Thu, 17 May 2012 06:00:59 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3728</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>There is a list of method resolution approach for virtual extension methods explained here. One of the interesting ones is when a class implements multiple interfaces and say 2 of the interfaces have same method signature but different implementations. But before that, lets look at a case where the class implements an interface, say I1 [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>There is a list of method resolution approach for virtual extension methods explained <a href="http://www.javabeat.net/2012/05/virtual-extension-or-defender-methods-in-java-8/" title="Virtual extension methods" target="_blank">here</a>. One of the interesting ones is when a class implements multiple interfaces and say 2 of the interfaces have same method signature but different implementations.<br />
But before that, lets look at a case where the class implements an interface, say I1 and I1 in turn extends another interface I2 and both I1 and I2 have a method with exact same signature. How is the method invocation using the instance of the implementing class handled?<br />
For this lets look at the following example:</p>
<pre class="brush: java; title: ; notranslate">
public class DefenderMethodsResolution{
  public static void main(String[] args){
    MySuperClass obj = new MySuperClass();
    System.out.println(obj.findProduct(4,5));
  }
}
class MySuperClass implements SpecialMathOperator{
  
}

interface SpecialMathOperator extends MathOperator{
  public int findProduct(int a, int b) default{
    return MathOperatorHelper.findProductUsingSum(a,b);
  }
}
interface MathOperator{
  public int findProduct(int a, int b) default{
    return MathOperatorHelper.findProduct(a,b);
  }
}
class MathOperatorHelper{
  public static int findProduct(int a, int b){
    System.out.println(&quot;Finding product by multiplying&quot;);
    return a*b;
  }
  
  public static int findProductUsingSum(int a, int b){
    int product = 0;
    System.out.println(&quot;Finding product by iterative sum&quot;);
    for (int i=0;i &lt; b; i++){
      product += a;
    }
    return product;
  }
}
</pre>
<p>The output for the above is:</p>
<pre class="brush: bash; title: ; notranslate">
javac DefenderMethodsResolution.java 
java DefenderMethodsResolution 
Finding product by iterative sum
20
</pre>
<p>It clearly shows that in this case the method resolution is handled by neglecting the super Interface and considering the more specific sub Interface provided sub interface is overriding (I dont know the exact term to use here) the method. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>When one thinks of Interfaces having code, then the first thing that comes to the mind is &#8220;<a href="http://en.wikipedia.org/wiki/Diamond_problem" target="_blank">Deadly Diamond of Death</a>&#8220;. Lets see how this is tackled by the compiler. Lets go ahead and slightly edit the code to remove the extends from the SpecialMathOperator interface and make MySuperClass implement both the interfaces. [I know this is not the very best examples, but I think good enough to explain the concept?]</p>
<pre class="brush: java; title: ; notranslate">
public class DefenderMethodsResolution{
  public static void main(String[] args){
    MySuperClass obj = new MySuperClass();
    System.out.println(obj.findProduct(4,5));
  }
}
class MySuperClass implements SpecialMathOperator,MathOperator{
  
}

interface SpecialMathOperator {
  public int findProduct(int a, int b) default{
    return MathOperatorHelper.findProductUsingSum(a,b);
  }
}
interface MathOperator{
  public int findProduct(int a, int b) default{
    return MathOperatorHelper.findProduct(a,b);
  }
}
class MathOperatorHelper{
  public static int findProduct(int a, int b){
    System.out.println(&quot;Finding product by multiplying&quot;);
    return a*b;
  }
  
  public static int findProductUsingSum(int a, int b){
    int product = 0;
    System.out.println(&quot;Finding product by iterative sum&quot;);
    for (int i=0;i &lt; b; i++){
      product += a;
    }
    return product;
  }
}
</pre>
<p>Trying to compile the above code we would get:</p>
<pre class="brush: bash; title: ; notranslate">
$javac DefenderMethodsResolution.java 

javaDefenderMethodsResolution.java:4: error: 
reference to findProduct is ambiguous, 
both method findProduct(int,int) in MathOperator 
and method findProduct(int,int) in SpecialMathOperator match
    System.out.println(obj.findProduct(4,5));
                          ^
DefenderMethodsResolution.java:7: error: 
class MySuperClass inherits unrelated defaults for findProduct(int,int)
from types SpecialMathOperator and MathOperator
class MySuperClass implements SpecialMathOperator,MathOperator{
^
2 errors
</pre>
<p>So the compiler doesn&#8217;t allow the compilation of such code thereby eliminating the Deadly Diamond of Death problem. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/resolution-of-the-invocation-of-virtual-extension-methods-in-java-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Virtual Extension Methods(or Defender Methods) in Java 8</title>
		<link>http://www.javabeat.net/2012/05/virtual-extension-methods-in-java-8/</link>
		<comments>http://www.javabeat.net/2012/05/virtual-extension-methods-in-java-8/#comments</comments>
		<pubDate>Wed, 16 May 2012 02:34:55 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3716</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>As part of the JSR-335 (Project Lambda) which adds closure support to Java language, there were quite a few changes in the language to support the use of closures in the existing Java APIs (Collection APIs to a large extent). One such change is the introduction of Virtual Extension Methods. We all are aware of [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>As part of the JSR-335 (Project Lambda) which adds closure support to Java language, there were quite a few changes in the language to support the use of closures in the existing Java APIs (Collection APIs to a large extent). One such change is the introduction of Virtual Extension Methods. </p>
<p>We all are aware of the fact that the interfaces don&#8217;t contain any implementation for the methods. To provide support for new APIs which support the use of closures and also which can run on Multi core platforms there has to be some way to add these APIs to existing classes. For example, methods like forEach, map, reduce, filter which act on a collection can be added to the Collection class directly or create a new interface and let all the collection API implement them or leave it to the user of the API to implement the new interface. The first 2 approaches would lead to breaking lots of existing code because of the lack of implementation of these new methods in the interface. The last approach is possible, but it doesn&#8217;t enhance the collection API out of the box. </p>
<p>The team which handles JSR-335 thought of a way to add default implementation to the interfaces, which gives an option for the implementor to override the method or to leave it as is. This way new APIs can be added to the Collection class without breaking the existing code and yet provide the full support of the closures to the existing code. One can read in depth about Virtual Extension Methods <a href="http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf" title="Virtual extension methods" target="_blank">here</a>. </p>
<p>Lets see an example of a virtual extension method: </p>
<pre class="brush: java; title: ; notranslate">
interface TestInterface{
  public void testMe();
  
  public void aDefaulter() default{
    System.out.println(&quot;Default from interface&quot;);
  }
}
</pre>
<p>Using the &#8220;default&#8221; keyword we can add new methods to the existing interface and allowing the implementing classes to use this default implementation if they don&#8217;t override. Something like:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
public class DefenderMethods{
  public static void main(String[] args){
    InterfaceImplementer imp = new InterfaceImplementer();
    imp.testMe();
    imp.aDefaulter();
  }
}
class InterfaceImplementer implements TestInterface{
  public void testMe(){
    System.out.println(&quot;Hello World!&quot;);
  }
}
</pre>
<p>The output for above program would be:</p>
<pre class="brush: bash; title: ; notranslate">
~/javaP/java8$ javac DefenderMethods.java 
~/javaP/java8$ java DefenderMethods 
Hello World!
Default from interface
</pre>
<p>Moving further, we can override the aDefaulter method in its implementing class, something like</p>
<pre class="brush: java; title: ; notranslate">
class InterfaceImplementer implements TestInterface{
  public void testMe(){
    System.out.println(&quot;Hello World!&quot;);
  }
  
  public void aDefaulter(){
    System.out.println(&quot;Defautler overridden from class&quot;);
  }
}
</pre>
<p>for which the output will be:</p>
<pre class="brush: bash; title: ; notranslate">
~/javaP/java8$ javac DefenderMethods.java 
~/javaP/java8$ java DefenderMethods 
Hello World!
Defautler overridden from class
</pre>
<p>The bytecode generated for the DefenderMethods class still uses invokevirtual opcode for invoking the default method, which indicates its treated like any other usual interface method in its invocation. </p>
<p>There&#8217;s lot more to this concept like overriding rules, method invocation rules which I would like to cover in subsequent posts. And also sample code from the JDK 8 which uses this feature. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/virtual-extension-methods-in-java-8/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Using Lambda Expressions of Java 8 in Java FX event handlers</title>
		<link>http://www.javabeat.net/2012/05/using-lambda-expressions-of-java-8-in-java-fx-event-handlers/</link>
		<comments>http://www.javabeat.net/2012/05/using-lambda-expressions-of-java-8-in-java-fx-event-handlers/#comments</comments>
		<pubDate>Mon, 14 May 2012 02:20:45 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java FX]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3690</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Note: The Project Lambda (JSR-335) to be added in Java 8 is evolving and the sample here is how one can use Lambdas with the current Java8 build downloaded from here. I will try to update the sample if there are any changes in the API in future. I thought it will be good to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>Note: The <a href="http://openjdk.java.net/projects/lambda/" title="Project Lambda" target="_blank">Project Lambda (JSR-335)</a> to be added in Java 8 is evolving and the sample here is how one can use Lambdas with the current Java8 build downloaded from <a href="http://jdk8.java.net/lambda/" title="Java 8 Binaries" target="_blank">here</a>. I will try to update the sample if there are any changes in the API in future</em>. </p>
<p>I thought it will be good to get a peak of how Lambda Expressions can be used with JavaFX or for that matter any Single Abstract Method (SAM) types. </p>
<p>Lets build a sample with just one toggle button and change the text of the toggle as and when it is selected/un-selected.<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/05/javafxLambda1.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/05/javafxLambda1.png" alt="" width="206" height="206" class="aligncenter size-full wp-image-3691" /></a></p>
<p>The code with the current Java -7 version would be:</p>
<pre class="brush: java; title: ; notranslate">
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleButtonBuilder;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class LambdasWithJavaFx extends Application {
  public static void main(String[] args){
    Application.launch(args);
  }
  @Override
  public void start(Stage stage) throws Exception {
    BorderPane root = new BorderPane();
    ToggleButton button = new ToggleButton(&quot;Click&quot;);

    final StringProperty btnText = button.textProperty();
    button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
      @Override
      public void handle(ActionEvent actionEvent) {
        ToggleButton source = (ToggleButton) actionEvent.getSource();
        if (source.isSelected()) {
          btnText.set(&quot;Clicked!&quot;);
        } else {
          btnText.set(&quot;Click!&quot;);
        }
      }
    });
  
    root.setCenter(button);

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setWidth(200);
    stage.setHeight(200);
    stage.show();
  }
}
</pre>
<p>The main focus would be on the EventHandler set for the ToggleButton, henceforth I would just show that part of the above code. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets see how we can use the Lambda expression to update above code. </p>
<pre class="brush: java; title: ; notranslate">
button.setOnAction((ActionEvent event)-&gt; {
  ToggleButton source = (ToggleButton) event.getSource();
  if (source.isSelected()) {
    btnText.set(&quot;Clicked!&quot;);
  } else {
    btnText.set(&quot;Click!&quot;);
  }
});
</pre>
<p>The only method in the EventHandler class is the handle(Event event) method and in the above example we just write the body and the parameter declaration for the method and remove all the unnecessary instantiation code. </p>
<p>We can remove the type declaration for the event, as the compiler will infer the type from the context. The context here is the Action event and hence the EventHandler expects a ActionEvent and thereby the event reference is inferred to be of ActionEvent type.</p>
<pre class="brush: java; title: ; notranslate">
button.setOnAction((event)-&gt; {
  ToggleButton source = (ToggleButton) event.getSource();
  if (source.isSelected()) {
    btnText.set(&quot;Clicked!&quot;);
  } else {
    btnText.set(&quot;Click!&quot;);
  }
});
</pre>
<p>This is just a peek at the Lambda expressions to be introduced in Project Lambda (JSR-335). I would take some time to dive a bit into detail of Lambda expressions. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/using-lambda-expressions-of-java-8-in-java-fx-event-handlers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
