Sunday, November 30, 2014

Java SE 8 new features tour: Traversing, filtering, processing collection, & methods enhancements with Lambda

Cleaner, readable, and powerful coding with lambda expressions.....

In this article of the “Java SE 8 new features tour” series, we will deep dig into explanation, and exploring the code, on how to traverse the collections using lambda expression and with method references, filtering them with predicate interface, implementing default methods in interfaces, and finally implementing static methods in interfaces.

In the previous article “Functional programming with Lambda Expression”; I have deeply dived into understanding lambda expressions. I have shown you a few different uses of Lambda Expressions. They all have in common the implementation of functional interfaces. I have also explained how the compiler is inferring information from code, such as specific types of variables and what is really happening in the background.

Source code is hosted on my Github account: Clone it from here.

Table of Content:

  1. Traversing collections with lambda expressions.
  2. Filtering collections with predicate interfaces.
  3. Traversing collections with method references.
  4. Implementing default methods in interfaces.
  5. Implementing static methods in interfaces.

1- Traversing collections with lambda expressions.

In Java SE 8, you can use lambda expressions to traverse a collection of items. Examples of collections include lists, maps, and sets. All of these data types implement an interface called iterable. To understand the code I'm about to show you, let's start in the documentation. I'm working a class called under package. I'll right click into the method name readAllLines and then Show Javadoc.

It returns List class that extends a number of interfaces. This is the one I'm interested in called iterable. This interface was added in Java SE 5. And it has a method called iterator. That returns an instance of an Iterator interface that you can use then to loop through the contents of a collection. But in Java SE 8 there were a couple of new methods. One called forEach, and one called spliterator. I'm going to focus on the forEach method.

It accepts an instance of a functional interface, called Consumer. The consumer interface has a single abstract method, named accept. And by implementing this interface and its single abstract method, you can add code that operates on an item in the collection.

So, let's go back to the code. In the class, I'm traversing this lines collection, this array list of strings representing the contents of a file, twice. In first version, starting at line 51, I'm using a forEach loop, it's a simple bit of code, and it creates a line String variable for each item in the list and then executes whatever code is needed.

At line 58, I'm using another approach, calling the iterator method of the collection. Getting an iterator object and then looping with a while code block, calling the iterators has next method. Now both of these bits of code have worked fine going all the way back to Java 5, but I'll show you what this might look like with a lambda expression and the forEach method. In Java 8, I'll start with this forEach method.

Starting at line 65 I'll reference my lines collection and call the new forEach method. And again it's going to receive an instance of the Consumer interface. Because Consumer is a functional interface, I can use a lambda expression. The Consumer interface's accept method requires a single argument of the appropriate data type. Because lines variable is declared as a list of strings, I have to pass in a string as the argument.

I'll pass it in with a name of line. Then I'll add my lambda operator, the arrow token. And I'll add my system output here, and pass in line.

And you can clean up the code a bit by removing old traversals. And now this single line of code replaces the three lines of the forEach loop. I'll make a copy of this code and move down here to the version that's using an iterator. And I'll select those lines of code and comment them out. And paste in my lambda expression version. So when you replace an iterator, you're replacing four lines of code with a single line.

More advanced you can use Stream with collections, Streams supports a sequence of elements supporting sequential and parallel aggregate operations. Normally it is used as the following:

Now save and run the code and see that it behaves exactly the same as it did before, but just with less code. So this is just another option for traversing collections. You can use forEach loops. You can use iterator objects and now you can use the forEach method with a lambda expression.

2- Filtering collections with predicate interfaces.

In addition to the new lambda syntax, Java SE 8 adds a number of new functional interfaces. One of the most useful is called the Predicate Interface. An interface that has a single boolean method named test, which you can use to wrap up your conditional processing, and make conditional code a lot cleaner. I'll show you how to use the predicate interface in this project.

Starting in the class named FileDirFilter class in package, I've declared a method called predicateInInnerClass.

I will use NIO.2 DirectoryStream class, to get a specific path entries stream, which in our case is declared as:

Now my goal is to filter this stream and only display certain entries, which are directories. You can use the predicate interface either with inner class syntax or with lambda syntax.

I'll start with inner class syntax. In predicateInInnerClass method, I'll declare an instance of the predicate interface. I'll type the name of the interface and press Ctrl+Space. And choose the interface from the list. It's a member of the package Java.util.function, and you'll find a lot of other new functional interfaces there as well. This interface needs a generic type declaration. I'll set that to the name Path class. And I'll name the predicate, dirsFilter.

Now, for inner class syntax, I'll start with the new keyword, and I'll press Ctrl+Space and choose the constructor for the predicate interface. When I choose that, NetBeans automatically implements the single abstract method, test. Because I declared my predicate with a generic type of Path, the test method accepts a single argument of that type as well. Now, I'm going to implement the method. I'm going to change the name of the path object being passed in to just "t".

I'll set the return statement to use a very simple criteria. I'll add a set of parentheses to wrap my condition. And I'll set the condition to isDirectory(t, NOFOLLOW_LINKS). So now my predicate object encapsulates my test, and the test method can be used to determine whether I want to process an object from my collection.

The next step is to traverse the collection. And you can do this in a number of ways with a forEach loop, an iterator object, or with the new forEach method.

I'll use the classic forEach loop. I'll type foreach and press Ctrl+Space, and choose the foreach code template. Within the for loop, I'll use an if statement. And I'll set the condition to use the dirsFilter object that I just declared. I'll call dirsFilter.test. I'll pass in the file object that I'm declaring in foreach loop. And then if the condition is true, I'll use system output and I'll output the results of calling the getFileName method of the file object.

I'll save and run that code. And I only see full path of paths of type directory. Now, if I want to change my condition, I can change the predicate object and rerun the code and it'll work fine. But our goal here is to make the code as concise and readable as possible. And for that, you might decide instead to use a lambda expression to implement this predicate interface. So let's go back to the code, and I'll fold this method, predicateInInnerClass, and unfold other method, predicateWithLambda.

Now I'm going to do very similar processing. But I'll declare my predicate object this time using a lambda expression. Once again, I'll type the name of the interface. I'll press Ctrl+Space and choose it from the list, and set its generic type. And I'll name this predicate object noFilter. Now I'll implement the interface using a lambda expression. I'll start with the signature of the method I'm implementing. That's the test method. And because I declared predicate with a generic type of Path, the argument is going to be an instance of path.

I'll just name it p. Then I'll add the arrow token, and then I'll implement my method with a simple conditional expression, to true to just return all defined path entries. And that's all I need. This single line of code replaced five or six lines of code in the inner class version. Next, I'll loop through the list and use the test method of the predicate object. This time, I'll use the doFilterAndPrintPath method passing in my predicate noFilter.

I showed how to use this method in previous lambda implementations. It's a new method that was added in Java SE 8. In implementation of doFilterAndPrintPath method I am using the forEach method of newDirectoryStream returned collection of paths, I'll start with the name of the object I'm passing in as an argument. This time I won't wrap it inside parentheses just to show you a difference in syntax. Then I'll add the arrow token and a pair of braces. Within the braces I'll use an if statement. And I'll pass in my condition, which again the predicate's test method. I'll use pred.test, and I'll pass in the path object.

And if the condition is true, I'll use system output. And I'll output the path object file name. I'll save and run the code. And there is the result. Once again, I'm displaying all entries. But what if I want to deal with more than one possible condition? Well this is the great thing about lambda syntax and the predicate interface.

You can make as many predicate objects, as you want, each representing a different condition.

So I'm going to duplicate this line of code, and I'll change the name of the new one to hiddenFilter. And I'll change its condition to show only hidden files and directories. To make it really easy to pass in whichever predicate I want, I'll take this code that's traversing the collection, and put it into its own separate method. We already did that in doFilterAndPrintPath method.

Now, the method doesn't know which predicate it's going to get, so I'm refactored the name of the predicate object in the method to just pred. And now, my existing code is passing in hiddenFilter, so I'll run that. And I get all hidden files and directories. And then I’ll change the predicate object that I’m passing in to timeFilter, and I’ll run the code again.

And this time I get all files and directories that is modified today. So this is how you can use the new predicate interface and lambda expressions to encapsulate your conditions in individual objects. And then pass those objects into your own methods for processing.

I won't cover a lot of the other new functional interfaces in Java SE 8 in detail, but I encourage you to investigate the package that the predicate interface is a part of java.util.function. You'll find a lot of new useful interfaces there.

And because they're all functional interfaces, they can all be implemented with lambda expressions.

3- Traversing collections with method references.

In addition to Lambda expressions, Java SE 8's Project Lambda also adds method references to the language. A method reference gives you a way of naming a method you want to call, instead of calling it directly. And just like Lambda expressions, the goal is to make your code more concise and more readable.

I'll demonstrate this in this class named MethodReference under package

You can use method references on four kinds of methods:

  1. Static methods of any class.
  2. Instance methods of a particular object.
  3. Instance methods of an arbitrary object, in which case you would refer to it just like it was a static method.
  4. And references to constructor methods.

I'll start with static methods. In this code, I have a FilesDirTests class, and my goal is to check wither a specific file is accessible or not. I'm going to create a method that does some comparisons to a path class. Now you could put this method anywhere you like, and developers will differ about the best place to put it, but I'm going to create the method as a static method of my FilesDirTests class.

I'll open the class and I'll place this new method. I'll declare it as public and static, and set its return data type to boolean. I'll name the method isAccessible. And the method will accept reference to path class. I'll name it p. This method will know that the goal is to compare path against some accessibility methods defined in java.nio.file.Files class. And just like the test method of the Predicate interface, this will return a true if the path is accessible, or false to indicate that path is not accessible.

I'll save that change, and now I'll go to my class MethodReference. To test accessibility of a given path files, I once again use the doFilterAndPrintPath(Predicate<Path> pred) method. I'll call it inside doPrint method. The defined path is used inside doFilterAndPrintPath method. And for the predicate object, I'll use a method reference. It'll look like this, I'm referring to a static method, and so I’ll start with the type, the class that contains the static method.

Then I'll put in the double colon operator, that's how you separate the type or the object from the name of the method that you're calling. And then I'll pass in the name of the method, isAccessible. Now here's why this is working. This method, the doFilterAndPrintPath method, is expecting an instance of the predicate interface. That interface has a single abstract method, which expects one value. I'm calling a method that expects one value. And returning a data type that can be used by the test method.

The doFilterAndPrintPath will traverse the path files, and output the values according to the test. Save the change, and run the code, and there's the result. Opppps There is no result? No files printed? This is because isAccessible has test condition that will make the test fails, which is isExecutable method.

So that's a static method reference. If you prefer, you can use method references with instance methods. To do this, I'm going to go down at the end of MethodReference class and add the following two methods:

In this class, in the main method, I'm creating an instance of the current class, and then calling it doFilterAndPrintPath method. By the time I get down here, all of the data and the methods are instance members, rather than static members.

Because main is a static method, so we can’t use this keyword, as alternative syntax you can use this keyword as reference inside object instance methods.

And just as I did before, I'll save and run, and there's the result. So method references are a simple way of making your code incredibly concise.

4- Implementing default methods in interfaces.

Prior to Java SE 8, interfaces could contain abstract methods and constant declarations, but you couldn't provide fully implemented methods that would be inheritable.

I'm working in a package called And in this application, I have an interface named VehicleInterface.Java. It has eight abstract methods, in interfaces all abstract methods are soon to be public, so I haven't included the public keyword and these are basic getters and setters.

Then I've a class named and this class has the setters and the getters implemented. And a constructor method that makes it easy to instantiate the class.

And then I have a main class called In this code, I'm filtering a list of cars using a predicate object, and then, display cars. I'm putting together a string named info and outputting it to the console. So, I'm going to refactor this code using a new capability of Java SE 8 that lets me add something called a default method to an interface.

When you add a default method to an interface, you can add its full implementation. And then, any class that implements that interface will inherit that method and you can call it itself or the method will be callable from anywhere else in the application because, just like the abstract methods, it will be public.

Back to VehicleInterface.Java I'll move the cursor below the abstract methods. And I'll start my method signature with the new keyword, default. The rest of the method will look exactly the same, as if I were implementing it in a class.

I'll start with the return type, then the name of the method. Next, I'll add the code, and it'll be a return statement that can concatenate the values of the name, model, car CC and the make year. Now, because this is an interface, I can't refer to private fields. You can't do that.

So, I'm just going to refer to the abstract methods, which I know will be implemented by the class itself. I'll call getName, getModel, getCC. Then I'll concatenate getMakeYear and a closing parenthesis.

I'll save that change and now that method is available to every class that implements the interface. I won't make any changes to the Car class. It already has that method. Then I'll go over here to my main class, use default method, and I'll change this code. I no longer need to create the string named Info, that's going to be done by the new method that the Car class has inherited. So, I'll comment out that line of code. And I'll replace the reference to the info variable with a call to the getInfo method.

But I'll call it as a member of the car object that I'm working with right now. I'll save the change and run the code. And there's the result. I'm successfully calling the getInfo method to get a string, a concatenation of the values of the name, model, CC and make year, and then I'm outputting it to the console using the code in my main class.

By using default methods, you can sometimes eliminate a whole layer of inheritance. Some developers, for example, in earlier versions of Java, might have created an interface, then a base class that implemented the interface and then a subclass that they would actually use in their code.

With this new capability, you might not need the base class at all and instead, can go directly to implementing the subclasses, inheriting the default methods directly from the interfaces.

5- Implementing static methods in interfaces.

I previously described how to add default methods to interfaces, which are fully implemented and are inherited by implementing classes. In Java SE 8, you can also add fully implemented static methods to interfaces. Just as with default methods, the goal is to let you eliminate inheritance layers and simplify your applications.

I'm working in a package called Just as in the earlier project, the one for default methods, the main class, which is called StaticMethod here, has code that gets the name, model, CC and make year from a car object.

It's at line 47 in this class. My goal is to take this code and move it to a static method, but instead of adding it to a base class or other concrete class, I'm going to add it to an interface. Something I wasn't able to do in earlier versions of Java. I'll take this code and copy it to the clipboard. Then, I'll open the interface, named Just as before, I'm starting with a set of abstract method declarations. Now, I'll place the cursor after those abstract method declarations and I'll start with the keyword static.

Just as with the default method and the abstract methods, this will be a public method automatically. I don't need to declare it. It'll return a string and I'll name it getVehicleInfo. Now because this is a static method, it can't refer to the instance methods declared above. So, I'm going to pass in an instance of the Car object. Then I'll provide the return keyword and I'll paste in the code from before and I'll clean this up so that now I'm returning the name, model, CC and make year and the closing parenthesis.

Now this static method is available from anywhere in the application. Just as before, I don't need to do anything to my Model class. That's called car, because all the code that's going to be getting the string and outputting it, is already available in the interface.

I'll go back to my main class, use static method, and now, instead of putting together this string here, I'll call the interface using the interface's name,, then I'll call the new static method, getVehicleInfo and pass in the Car object, which is c.

And I'll save the change and run the code. And there's the result. Functionally, it's exactly the same as using a default method, or putting this code into the Car class, or having it right here at the top level in the main class.

The goal of both default and static methods is just to give you more options in putting together the inheritance model for your application. Using both default and static methods, you can eliminate entire inheritance layers of your application and enormously simplify the coding model, making the application easier to code and to maintain.

  1. The Java Tutorials, Lambda Expressions
  2. JSR 310: Date and Time API
  3. JSR 337: Java SE 8 Release Contents
  4. OpenJDK website
  5. Java Platform, Standard Edition 8, API Specification

Saturday, September 20, 2014

NetBeans: 8.0.1 Released with bunch of out-of-the-box tools = productivity++

In every NetBeans release it provides out-of-the-box tools that leverage the java standards and other tools toward the web standards, alongside great papular market tools that increases developer daily productivity.

NetBeans editor analyzes code to work efficiently with great tips and refactoring templates for more clear and cleaner code, provides migration from other JDKs toward Java 8, and it works for Java SE 8, Java SE Embedded 8, and Java ME Embedded 8.

The IDE also has a range of new enhancements that further improve its support for Maven and Java EE with PrimeFaces; new tools for HTML5, in particular for AngularJS; and improvements to PHP and C/C++ support.

Beside that the IDE has an interesting new features especially for JavaScript developers whom seeks for writing modular code, it comes with built-in support RequireJS, that provides modularity and enterprise features for JavaScript.

More interesting features:

  1. You can now debug your JavaScript files with Karma.
  2. Node.JS and Bower built-in integrations let you install modules directly within the IDE.
  3. Support for latest application servers GlassFish 4.1, Tomcat 8.0.9, WildFly 9, and WebLogic 12.1.3
  4. IDE comes with pre-bundled GlassFish 4.1 and Tomcat 8.0.9
  5. Latest PrimeFaces v5.0 framework bundled with IDE.
  6. Improved Git support

GlassFish 4.1 is now Java SE 8 certified, so you can develop your Java EE 7 projects with JDK 8 for more modularity and cleaner code, yeah have fun :)

For the complete set of bunch of tools please visit NetBeans IDE 8.0.1 Information

Hungry to code, so what are you waiting for?? , Download Netbeans IDE

Sunday, August 10, 2014

IDE: 5 most favorite NetBeans features

Development with pleasure....
NetBeans has many interesting features that make development very easy, with few steps, and makes for a very productive environment, in terms of getting your product to market very quickly.

It is very hard to limit my talking to only five features, while this IDE has tons of interesting features. But here I am going to mention my most favorite 5 features I am daily using in my development process on many platforms:

  1. It is the reference development implementation IDE:

    I am a JCP (Java Community Process), EC (Executive Committee), a JSRs (Java Specifications Request) adopter and FishCAT (Glassfish Community Acceptance Testing) contributor especially in Java, SE & EE world. While I am in early phases of testing the specifications, I need an IDE which support those technologies and made it easy to test and develop them, to report bugs, enhancements and confirms that JSRs Specs are valid against RIs, and with other JSRs on latest RI Application server like Glassfish.

    NetBeans offered all of this for us to streamline the process, with almost a nightly and weekly builds alongside JSRs RIs builds, which we use to test previously mentioned RIs betas.

    The most interesting part of the story here is when we released Java EE 7 on last Mid of June 2013; there was already NetBeans 7.4 was generally available released to fully support development of Java EE 7 technologies. And this happens also for JDK 8 when it released 18-March 2014, there was NetBeans 8.0 fully support Java SE 8.0.

  2. Android Mobile development made easy:

    NetBeans shipped with a very great support for mobile development either it was pure Android development in term of this is a Java Based IDE or Hybrid development in term of frontend technology support (HTML5, CSS3 and JavaScript).

    With a very productive plugin NBAndroid you can develop a pure Android project compatible with original ADT SDK (Android Development Toolkit) project structure, test, emulate and deploy on emulators as well as native devices at the same time. You should give it a try if you interested in mobile development.

    Create a new Project:
    Identify Properties:
    Created project:
    Runs On Android Emulator:
  3. Hybrid Mobile development support:

    Hybrid mobile development is never made easy as now in NetBeans nowadays, NetBeans introduced a hybrid mobile development based on Cordova open source mobile framework. Which is one of the most popular frameworks to develop hybrid mobile applications.

    While NetBeans gives a great and solid support for frontend engineering technologies like JavaScript, HTML5, CSS3, Frameworks like AngularJS, NodeJS, and jQuery core, mobile, and UI … etc.

    Which made it easy to develop a Hybrid based mobile applications for both Android and iOS in one shoot with few clicks. Without context-switching to other IDEs to accomplish the task.

    It has complete support for Apple iOS development toolkit and Android ADT SDK, therefore you can test your application locally for mobile web and on emulators/devices of both mobile OSs, then export final product either it was .apk binary for android or .ipa for iOS, for final deployment on Apple store or Google play store.

    Creating the project:
    Choosing template:
    Identifying project properties:
    Choosing deployment method:
    Deployed on iOS simulator:
  4. JavaScript libraries in one place:

    If you are a frontend engineer, then you got the right choice, yes this IDE is for you, I know you need to develop a modern web application, but wait this needs many JavaScript modules and libraries to do it.

    One among the very panic tasks in web development nowadays, is to search for JavaScript tools and setup your project for them, then download each JavaScript libs from different sites with there resources and support libs, in addition you have also to manage their updates to fix problems or get a new feature.

    NetBeans comes with a build in tool that allows you to get your JavaScript libraries in one shoot from the IDE directly and mange their updates from the same place.

    You will find almost all JavaScript libs you need, and you can filter your choice from the tool to pic up the right libs you need for your project, and where to put them in your project.

    As mentioned in first picture the libs were updated on Apr 26, 2014, just click and will updates all libs to today releases.

    It saves me a bunch of site visiting and worrying about updating them, and even adding new ones in future of the project.

    The JavaScript tool:
    Pickup and filter your choices:
  5. SOAP based client/Web Services in one click:

    I am working in government environment, which requires much integration between systems either directly or through a G2G (Government-to-Government) hub, each one needs a specific integration requirements.

    If it is directly, you have to define you web service annotations on interface based on your backend EJB session bean interface or separate endpoint interface to decouple your Endpoint from your façade, then generate WSDL to be consumed by others.

    Other scenarios is to go to a Top-Down approach, in developing WSDL first to be certified on G2G hub based on their standards, then generate service endpoint interface from them.

    Lately I have been asked to develop a Pension G2G WSDL definition and at the same time generate endpoint service interface to begun the testing in one week.

    I have accomplished this task in 3 days using NetBeans, it has a tremendous support for XML, XSD development, and after finishing the WSDL definition, I need to confirm a correct endpoint service creation, Before publishing service WSDLs to G2G authors.

    Okay from NetBeans I have created a Web Service from WSDL, passed the WSDL and click finish, that’s all.

    The surprise was it generates the service endpoint correctly as WSDL def. and at the same time created Service ports and client to test service in one shoot.

    All I have to do is to implements my service endpoint operations and huryaaaa finished my task.

    Adding WSDL and Identifies project attributes:
    Generated Service endpoint:

Thanks for NetBeans team for such support and made it a development with pleasure.

Monday, June 30, 2014

Java SE 8 new features tour: Functional programming with Lambda Expression.

Understanding lambda expressions....

This article of the “Java SE 8 new features tour” series will deep dive into understanding Lambda expressions. I will show you a few different uses of Lambda Expressions. They all have in common the implementation of functional interfaces. I will explain how the compiler is inferring information from code, such as specific types of variables and what is really happening in the background.

In the previous article “Java SE 8 new features tour: The Big change, in Java Development world”, where I have talked about what we are going to explore during this series. I have started by an introduction to Java SE 8 main features, followed by installation process of JDK8 on both Microsoft windows and Apple Mac OS X platforms, with important advices and notice to take care of.

Finally, we went through a development of a console application powered by Lambda expression to make sure that we have installed Java SE 8 probably.

Source code is hosted on my Github account: Clone from HERE.

What is Lambda expression?

Perhaps the best-known new feature of Java SE 8 is called Project Lambda, an effort to bring Java into the world of functional programming.

In computer science terminology;

A Lambda is an anonymous function. That is, a function without a name.
In Java;
All functions are members of classes, and are referred to as methods. To create a method, you need to define the class of which it's a member.

A lambda expression in Java SE 8 lets you define a class and a single method with very concise syntax implementing an interface that has a single abstract method.

Let's figure out the idea.

Lambda Expressions lets developers simplify and shorten their code. Making it more readable and maintainable. This leads to remove more verbose class declarations.

Let's take a look at a few code snippets.

  1. Implementing an interface:

    Prior to Java SE 8, if you wanted to create a thread, you'd first define a class that implements the runnable interface. This is an interface that has a single abstract method named Run that accepts no arguments. You might define the class in its own code file. A file named by And you might name the class, MyRunnable, as I've done here. And then you'd implement the single abstract method.

    In this example, my implementation outputs a literal string to the console. You would then take that object, and pass it to an instance of the thread class. I'm instantiating my runnable as an object named r1. Passing it to the thread's constructor and calling the thread's start method. My code will now run in its own thread and its own memory space.

  2. Implementing an inner class:

    You could improve on this code a bit, instead of declaring your class in a separate file, you might declare it as single use class, known as an inner class, local to the method in which it's used.

    So now, I'm once again creating an object named r1, but I'm calling the interface's constructor method directly. And once again, implementing it's single abstract method. Then I'm passing the object to the thread's constructor.

  3. Implementing an anonymous class:

    And you can make it even more concise, by declaring the class as an anonymous class, so named because it's never given a name. I'm instantiating the runnable interface and immediately passing it to the thread constructor. I'm still implementing the run method and I'm still calling the thread's start method.

  4. Using lambda expression:

    In Java SE 8 you can re-factor this code to significantly reduce it and make it a lot more readable. The lambda version might look like this.

    I'm declaring an object with a type of runnable but now I'm using a single line of code to declare the single abstract method implementation and then once again I'm passing the object to the Thread's constructor. You are still implementing the runnable interface and calling it's run method but you're doing it with a lot less code. In addition, it could be improved as the following:

    Here is an important quote from an early specs document about Project Lambda.
    Lambda expressions can only appear in places where they will be assigned to a variable whose type is a functional interface.

    Quote By Brian Goetz
    Let's break this down to understand what's happening.

What are the functional interfaces?

A functional interface is an interface that has only a single custom abstract method. That is, one that is not inherited from the object class. Java has many of these interfaces such as Runnable, Comparable, Callable, TimerTask and many others.

Prior to Java 8, they were known as Single Abstract Method or SAM interfaces. In Java 8 we now call them functional interfaces.

Lambda Expression syntax:

This lambda expression is returning an implementation of the runnable interface; it has two parts separated by a new bit of syntax called the arrow token or the Lambda operator. The first part of the lambda expression, before the arrow token, is the signature of the method you're implementing.

In this example, it's a no arguments method so it's represented just by parentheses. But if I'm implementing a method that accepts arguments, I would simply give the arguments names. I don't have to declare their types.

Because the interface has only a single abstract method, the data types are already known. And one of the goals of a lambda expression is to eliminate unnecessary syntax. The second part of the expression, after the arrow token, is the implementation of the single method's body.

If it's just a single line of code, as with this example, you don't need anything else. To implement a method body with multiple statements, wrap them in braces.

Lambda Goals:

Lambda Expressions can reduce the amount of code you need to write and the number of custom classes you have to create and maintain.

If you're implementing an interface for one-time use, it doesn't always make sense to create yet another code file or yet another named class. A Lambda Expression can define an anonymous implementation for one time use and significantly streamline your code.

Defining and instantiating a functional interface

To get started learning about Lambda expressions, I'll create a brand new functional interface. An interface with a single abstract method, and then I'll implement that interface with the Lambda expression.

You can use my source code project "JavaSE8-Features" hosted on github to navigate the project code.

  1. Method without any argument, Lambda implementation

    In my source code, I'll actually put the interface into its own sub-package ending with lambda.interfaces. And I'll name the interface, HelloInterface.

    In order to implement an interface with a lambda expression, it must have a single abstract method. I will declare a public method that returns void, and I'll name it doGreeting. It won't accept any arguments.

    That is all you need to do to make an interface that's usable with Lambda expressions. If you want, you can use a new annotation, that's added to Java SE 8, named Functional Interface.

    Now I am ready to create a new class UseHelloInterface under lambda.impl package, which will instantiate my functional interface (HelloInterface) as the following:

    Run the file and check the result, it should run and output the following.

    So that's what the code can look like when you're working with a single abstract method that doesn't accept any arguments. Let's take a look at what it looks like with arguments.

  2. Method with any argument, Lambda implementation

    Under lambda.interfaces. I'll create a new interface and name it CalculatorInterface. Then I will declare a public method that returns void, and I will name it doCalculate, which will receive two integer arguments value1 and value2.

    Now I am ready to create a new class Use CalculatorInterface under lambda.impl package, which will instantiate my functional interface (CalculatorInterface) as the following:

    Note the doCalculate() arguments, they were named value1 and value2 in the interface, but you can name them anything here. I'll name them v1 and v2. I don't need to put in int before the argument names; that information is already known, because the compiler can infer this information from the functional interface method signature.

    Run the file and check the result, it should run and output the following.

    Always bear in mind the following rule:
    Again, you have to follow that rule that the interface can only have one abstract method. Then that interface and its single abstract method can be implemented with a lambda expression.
  3. Using built-in functional interfaces with lambdas

    I've previously described how to use a lambda expression to implement an interface that you've created yourself.

    Now, I'll show lambda expressions with built in interfaces. Interfaces that are a part of the Java runtime. I'll use two examples. I'm working in a package called lambda.builtin, that's a part of the exercise files. And I'll start with this class. UseThreading. In this class, I'm implementing the Runnable interface. This interface's a part of the multithreaded architecture of Java.

    My focus here is on how you code, not in how it operates. I'm going to show how to use lambda expressions to replace these inner classes. I'll comment out the code that's declaring the two objects. Then I'll re-declare them and do the implementation with lambdas. So let's start.

    Let's look at another example. I will use a Comparator. The Comparator is another functional interface in Java, which has a single abstract method. This method is the compare method.

    Open the file UseComparator class, and check the commented bit of code, which is the actual code before refactoring it to lambda expression.

    As before, it doesn't provide you any performance benefit. The underlying functionality is exactly the same. Whether you declare your own classes, use inner or anonymous inner classes, or lambda expressions, is completely up to you.

In the next article of this series, we will explore and code how to traverse the collections using lambda expression, filtering collections with Predicate interfaces, Traversing collections with method references, implementing default methods in interfaces, and finally implementing static methods in interfaces.

  1. The Java Tutorials, Lambda Expressions
  2. JSR 310: Date and Time API
  3. JSR 337: Java SE 8 Release Contents
  4. OpenJDK website
  5. Java Platform, Standard Edition 8, API Specification

Monday, June 16, 2014

Java SE 8 new features tour: The Big change, in Java Development world.

I am proudly one of the adopt-OpenJDK members like others professional team members, but joined from last 8 months, during this period, we went through all the stages of Java SE 8 development, compilations, building, coding, and many discussions … etc., until we bring it to the life. And it is released on March 18th 2014 and it is now available for you.

I am happy to announce about this series “Java SE 8 new features tour”, which I am going to write it, supported with examples to streamline the Java SE 8knowledge gaining of most of new features, and APIs, development experience that will leverage your knowledge, enhancing the way you code, and increase your productivity as well. I hope you enjoy it ;) as I am doing when writing it.

We will take a tour of the new major and important features in Java SE 8 (projects and APIs), the platform designed to support faster, and easier Java development. We will learn about Project Lambda, a new syntax to support lambda expressions in Java code.

Checking the new Stream API for processing collections and managing parallel processing.

Calculating timespans with The DateTime API for representing, managing and calculating date and time values.

In addition to Nashorn, a new engine to better support the use of JavaScript code with the Java Virtual Machine.

Finally, I will also cover some lesser-known features such as new methods for joining strings into lists and other more features that will help you in daily tasks.

For more about Java SE 8 features and tutorials, I advise you to consult the Java Tutorial the official site and Java SE 8 java API documentation too.

The topics we are going to cover during this series will include:

  1. Installing Java SE 8, notes and advices.
  2. Introducing Java SE 8 main features, the big change.
  3. Working with lambda expressions and method references.
  4. Traversing collections with streams. Part 1, Part 2
  5. Calculating timespans with the new DateTime API (JSR 310)
  6. Running JavaScript from Java with Nashorn.
  7. Miscellaneous new features and API changes.
  1. Installing Java SE 8, notes and advices.

    1. Installing Java SE 8 on Windows

      In order to run Java SE 8 on Microsoft Windows, first check which version you have. Java SE 8 is supported on Windows 8, 7, Vista, and XP. Specifically, you'll need these versions. For Windows 8 or 8.1, you'll need the desktop version of Windows. Windows RT is not supported. You can run Java SE 8 on any version of Windows 7, and on the most recent versions of Windows Vista and Windows XP. On Server based versions of Windows, you can run 2008 and the 64-bit version of 2012.

      If you want to work on Java Applets you'll need a 64-bit browser, these can include Internet Explorer 7.0 and above, Firefox 3.6 and above, and Google Chrome which is supported on Windows, but not on Mac.

      You can download the Java Developer Kit for Java SE 8 from

      1. URL That will take you to the current Java home page.
      2. Click Java SE.
      3. Under Top Downloads. Then click the Download link for Java 8.

    2. Installing Java SE 8 on Mac

      In order to work with Java SE 8 on Mac OS X, you must have an Intel-based Mac running Mac OS X 10.7.3, that's Lion, or later. If you have older versions of Mac, you won't be able to program or run Java 8 applications. In order to install Java SE 8 you'll need administrative privileges on your Mac. And in order to run Java applets within a browser you'll need to use a 64 bit browser, such as Safari or Firefox.

      Google Chrome is a 32 bit browser, and won't work for this purpose.

      As described earlier on installing Java SE on windows, the same website has the MAC OS .dmg version to download and install. Actually contains all operating systems versions. However, our focus here would be on windows and MAC.

    Now you're ready to start programming with Java SE 8 on both Windows and MAC OS X platforms.

    After we have installed Java SE 8 probably, let's dive into the first point and have a look at Java SE 8 main features in a nutshell, to begin our coding tour on our favorite IDE.

  2. Introducing Java SE 8 main features, the big change.

    An overview of the JSR 337: Java SE 8 Release Contents
    Java SE 8 is a major release for the Java programming language and the Java virtual machine. It includes many changes. Some have gotten more coverage than others like Lambda expression, but I'm going to talk about both the major changes and a few of the minor ones.

    JSR 335: Lambda Expressions
    Probably the most attention has gone to Project Lambda, a set of new syntactical capabilities that let Java developers work as functional programmers. This includes lambda expressions, method references and a few other capabilities.

    JSR 310: Date and Time API
    There is a new API for managing dates and times. Replacing the older classes. Those older classes are still in the Java Runtime, but as you build new applications, you might want to move to this new set of capabilities, which let you streamline your code and be a little more intuitive in how you program. There are new classes to manage local dates and times and time zones and for calculating differences between different times.

    The Stream API
    Adds new tools for managing collections including lists, maps, sets, and so on.

    A stream allows you to deal with each item in a collection without having to write explicit looping code. It also lets you break your processing into multiple CPUs. So, for large, complex data sets you can see significant performance improvement.

    Project Nashorn
    The Nashorn JavaScript engine is new to Java SE 8 too. This is a completely new JavaScript engine written from scratch that lets you code in JavaScript but lets you integrate Java classes and objects.

    Nashorn's goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. This Project intends to enable Java developers embedding of JavaScript in Java applications via JSR-223 and to develop freestanding JavaScript applications using the jrunscript command-line tool.

    In the article on Nashorn, I'll describe how to run Nashorn code from the command line. But also how to write JavaScript in separate files, and then execute those files from your Java code.

    Concurrency API enhancements.
    There are also enhancements to the concurrency framework, which lets you manage and accumulate values in multiple threads. There are lots of smaller changes as well.

    String, numbers has new tools
    There are new tools for creating delimited lists in the string class and other new classes. There are tools for aggregating numbers including integers, lungs, doubles, and so on.

    Miscellaneous New Features
    There are also tools for doing a better job of detecting null situations, and I'll describe all of these during the series.

    And I'll describe how to work with files, using new convenience methods.

So, when is Java SE 8 available?
The answer is, now. It was released on March 18, 2014. For developers who use Java to build client site applications, the JavaFX rich internet application framework supports Java 8 now. And most of the Java enterprise edition vendors support Java 8 too. Whether you move to Java SE 8 right away depends on the kinds of project you're working on.

For many server and client site applications, it's available immediately.

Not for Android yet.
Android developers beware; Java SE 8 syntax and APIs are not supported in Android at this point.

It's only very recently that Android moved to some of the newest Java 7 syntax. And so, it might take some time before Android supports this newest syntax or the newest APIs. But for all other Java developers, it's worth taking a look at these new capabilities.

What about IDEs?
Java SE 8 is supported by all of the major Java development environments. Including Oracle's Netbeans, Intellij Idea, and Eclipse. For this series I'll be doing all of my demos in Netbeans, using Netbeans, version 8, which available to download from

However, before we start diving into this series, let’s check first that we have installed Java SE 8 probably, to start a new project under Netbeans, which will hold all of our code that we are going write during the series. Then develop a lambda code to test our project if it is working probably or not with Java SE 8 .

Alternatively you can download the series source codebase from my Github account, open it with Netbeans and follow what I am showing next, and in upcoming series code.

Project on Github:

Hello world application on Java SE 8 with Lambda expression.
Steps (not required if you navigating my code):

  1. Open NetBeans 8 --> from file --> New project --> from left, and choose Maven --> from right, and choose Java Application --> Click next.

  2. Follow the following screen shoot variables definition, or change to your favorite names and values --> then click finish.

  3. If everything wents okay you should have the following structure, on project navigator:

  4. Click on Project “Java8Features” --> Click File, from upper menu --> then, Project properties.

  5. Under Category --> From left choose Source, then check that “Source/ Binary format” is 1.8. --> From left open Build, and choose Compiler, then check that “Java Platform” is pointing to your current JDK 8 installation --> Click Ok.

  6. If JDK 8 not presents then go to tools --> chooses, Java Platforms --> Add Platform --> Then chooses Java Standard Edition --> then point to your installed JDK 8.

  7. Now our project configured to work with Java 8,Hurya let's do it, add some Lambda code.

  8. On Package “”, right click, and select New from menu --> Java Interface --> Name it Printable, under overview package “” --> click Finish.

  9. Implement Printable interface as the following:

  10. On the same package add the following class named “Print”, with main method (to run as application) as the following:

  11. Right click on Print class and choose Run. If every thing is okay, then you should see the following output.

  12. Congratulation your Java SE 8 project works fine, let’s explain what we have written.

    Most of this code would work on Java 7, but there's an annotation here that was added in Java SE 8, FunctionalInterface. If your Netbeans environment isn't correctly configured for Java 8, this annotation will cause an error because it won't be recognized as valid Java code. I don't see an error, so that's a good sign that Eclipse is working as I hoped.

    Next I'll open this class definition named This is a class with a main method so I can run it as a console application and it has a critical line of new Java 8 syntax.

    It's creating an instance of that functional interface I just showed you using a lambda expression, a style of syntax that didn't exist in Java prior to Java 8. I'll explain what this syntax is doing very early in the next article.

    But all you need to know right now is that if this code isn't causing any errors, then once again, Netbeans is recognizing it as valid Java syntax. I'm creating an instance of that interface and then calling that interface's print method. And so, I'll run the code.

    I'll click the Run button on my tool bar and in my console I see a successful result. I've created an object, which is an instance of that interface using a lambda expression. And I've called its method and it's outputting a string to the console. So, if this is all working, you're in great shape. You're ready to get started programming with Java SE 8 in Netbeans. If you had any problems along the way, go back to earlier steps and walk through the steps. One step at a time.

  1. The Java Tutorials, Lambda Expressions
  2. JSR 310: Date and Time API
  3. JSR 337: Java SE 8 Release Contents
  4. OpenJDK website
  5. Java Platform, Standard Edition 8, API Specification

Monday, June 9, 2014

Speaking activities during year 2014

Here are my speaking activities, during this year of 2014, Thanks for inviting organizations, JUGs, and international conferences.

I hope to see you all in my sessions, workshop, answers your questions and added value to you.

List of places, dates, and sessions titles:

Deliver and present the following talks in many conferences world wide, as part of sharing my experiences and evangelist the technologies especially JavaEE, JSRs, adopt-a-JSR, OpenJDK, Mobile development and others.
  1. Esprit JUG 2014 - Tunis, Tunisia. On the 7th & 8th of May

    Delivers the following sessions:
    1. What is new in Java SE, EE, ME, Embedded world, & new Strategy?
    2. Drive yourself, community with JCP & adopts to professionalism.
    3. Developing Native & Hybrid Android mobile Apps, with Netbeans 8.
    4. Yeah, TRUE real time web applications, no more hacks (a hack session).
    5. Hybrid Mobile development without IDE from CLI (Workshop).

  2. JCP executive committee F2F meeting 2014 - London, UK. On the 13th & 14th of May

    Delivers the following session:
    1. United Nations UNHCR/WFP case study (JavaEE, JavaCard, JavaSE success story).

  3. JEEConf 2014 - Kiev, Ukraine. On the 23th & 24th of May


    Delivers the following sessions:
    1. Yeah, TRUE real time web applications, no more hacks (a hack session).
    2. Developing Native & Hybrid Android mobile Apps, with Netbeans 8.

  4. 33rd Degree 2014 - Krakow, Poland. On the 9th to 11th of June.


    Delivers the following sessions:
    1. Architecting Hybrid mobile apps with PhoneGap.
    2. JavaSE NIO.2 API features, a walkthrough (The essential Stuff).

  5. JavaOne 2014 - San Francisco, California, USA. On the 28 Sep to 2 of October 2014.

    Delivers the following sessions:
    1. United Nations UNHCR/WFP case study (JavaEE, JavaCard, JavaSE success story).

  6. JMaghreb 3.0 2014 - Casablanca, Morocco. On the 7th & 8th of November

    Delivers the following sessions:
    1. Architecting Hybrid mobile apps with PhoneGap.
    2. Top 10 Key Performance Techniques for Hybrid mobile Apps.

Sunday, June 8, 2014

JEEConf 2014, Kiev, Ukraine trip report

Very busy May.

This May 2014 was a very busy month for me, I was so busy at work but thankfully I have finished all my heavy-duty tasks and left other managed tasks to my team to finish it till my back from my international trips.

My Trips

In last May 2014, first I went to Tunis, Tunisia, speaking at Esprit JUG Day 2014 on 7th and 8th of May, delivering the following 4 sessions:
1- What is new in Java SE, EE, ME, Embedded world, & new Strategy?
2- Drive yourself, community with JCP & adopts to professionalism.
3- Developing Native & Hybrid Android mobile Apps, with Netbeans 7.4+.
4- Yeah, TRUE real time web applications, no more hacks (a hack session).
5- Hybrid Mobile development without IDE from CLI (Workshop) (Cordova framework).
My JCP EC F2F meeting

After that I have traveled to London, United Kingdom, to attend my JCP executive committee F2F meeting 2014 on the 13th & 14th of May as I am a JCP EC member, and delivered the following session:

1. United Nations UNHCR/WFP case study (JavaEE, JavaCard, JavaSE success story).

Trip to Ukraine

On 23th and 24th I had the opportunity for the second time, to attend and speak at JEEConf 2014 in Kiev, Ukraine. This is my one of the favourite conferences I like to attends and share my experience there as well. As I was there in 2013. Among speakers from Ukraine there were a lot from other countries like UK, USA, Switzerland, Germany, Egypt (me), Greece, Sweden, Poland, Netherlands and Russia etc.


All my friends, colleagues, and work managers advised me to not travel to Ukraine, because of the political situation it has, my only words to reply are:
We already had this experience in Egypt since three years ago, so there is nothing to worry about ☺.
I love Ukraine, especially Kiev, because I have many friends there from attendees, speakers (Victor Polischuk), colleagues from Ukraine JUG Andrii Rodionov as I am EGJUG lead and MoroccoJUG member so we attends many JUG events together, and EBAM employees Olena Syrota.

Therefore I felt that I was in my country and not as a foreign guy.

Hanging out

After my arrival by a day before the event, I have decided to hangout alone to see the city and take some pictures. Then at the hotel reception I have found my friends I have met last year from Oracle Russia Speakers (Alexey Fyodorov, Alexander Belokrylov, and Sergey Kuksenko) and others (Gleb Smirnov from Deutsche Bank, Russia) and finally Ivan Krylov from Azul Systems Russia, then we hanged out together to have a dinner a Ukrainian local restaurant.

Also we went to Khreschatyk Midan (Square), where the revolution began, and here are some pictures

My talks

I have attended many English sessions, and delivered the following sessions as well:

1- Yeah, TRUE real time web applications, no more hacks (a hack session).

2- Developing Native & Hybrid Android mobile Apps, with Netbeans 8.

The first talk (Developing Native & Hybrid Android mobile Apps, with Netbeans 8.) went okay and I have found a lot of interesting questions, and response from people.

But for the second talk (Yeah, TRUE real time web applications, no more hacks (a hack session)) there were many attendees about 100+, and I couldn't take one photo to tweet it, so I have decided to take a panorama one as the following.

It was very interesting to them, and I heard many times that the talk was the best of the day. It was a master session and there were many very good and interesting questions (around 40+ questions) to answer (Thanks God, you helped me to answer all the question and satisfies the attendees).

Therefore at the end of the session, I got many Thanks cards about 41+ cards. It was a great feeling the all attendees had the experience of the talk, mastered the topic, and the hack code (application) get their interest. download it from here, download the zip file from File --> Download, it is netbeans based project.

I think both talks received a warm welcome from the audience, but I cannot be the judge of that, of course. I have just written down what I have heard, got (Thanks cards), and seen from their faces ☺ actions.

Event and Organizers

Thanks for event organizers you did a tremendous work. The hotel was very nice providing excellent services, breakfast, speedy Internet, and complementary shuttle service to any location you would like (I have chosen to drive me to the airport).

Its location was very near from the city centre, and most popular locations, restaurants, and metro stations. The event could be reached by just 4 stations about 13 min from the hotel.

Here are some pictures from my room and hotel:

And I had this great and tasty berry pie in my breakfast at my last day for me at Ukraine

Really the event was very well organized and managed, although the country passes by critical political situation.

I need to mention that there were even lunch for attendees as well as speakers, and many interesting activities. I am so happy to be part of the event successful story.

I had the opportunity to hang out with many speakers, friends, and EPAM employees, and I have enjoyed also the guided tour to many interesting places in Kiev for around three hours with the following speakers Peter Ledbrook, Nicolas Fränkel, Evgeny Borisov and his wife.

Talk to publish

After my return I got message from EPAM Educational head manager on my LinkedIn profile, they asked about my Websocket talk link, to mention it in EPAM magazine in article about JEEConf to be one of the most interesting talk in JEEConf 2014.

My hope

Thanks for this year invitation and looking forward to be part of JEEConf 2015 ☺.