Sri Lanka's First and Only Platform for Luxury Houses and Apartment for Sale, Rent

Thursday, April 3, 2014

Java 8 Features Part 2

In a previous post I covered the features Parallel Operations and Method References newly available in Java 8. But the most significant and effecting feature is the Lambda Expressions. Lambda Expressions is a vast subject and was available in many other programming languages for sometime now. Java being an Object oriented programming language (with the exception of primitives of course) didn't support this up until its 1.8.0 version.

Problem (Or at least lack of efficiency) : Java was always Object oriented mostly methods are merely used to implement behavior or provide getters or setters. And more importantly a method can not exists without it being inside of a Class. This is a strong OOP Principle and has been having no problem for developers also.

Except! when you want to do this;

    public static void main(String[] args) {
        new Thread(new Runnable() { 
            public void run() {
                System.out.println("Hello, World!");

Well this code doesn't look any harm but as you can see for Just to pass the implementation which is in the you need to create an anonymous class. In a scenario where you have different type of Classes and accepting Interfaces as arguments such in Swing ActionListener this can become a headache. Languages such as Javascript allows passing of functions around which eliminates this type of unnecessary codes. But Java didn't support it for good reasons.

Solution : Lambda Expressions to the Rescue! Lambda Expressions allows you to pass in Methods as if Java supports Global Methods. Enabling the flexibility of not defining anonymous classes and keeping the code clean and simple.

    public static void main(String[] args) {
        new Thread(() -> { System.out.println("Hello, World!"); }).start();

What the HTML! is that?. Your inner Java coder would have screamed looking at that code. But fear not, not only this code compiles but it also runs and produces the exact same result.

Basically Lambda Expressions enables the developer to define a method at the location of where it is required or have a reference to a Method (This was covered in previous post). This feature enables the developer to simplify the code. Lambda Expression is a really vast area and can not be covered in one blog post. So I highly recommend you to read the links in the references section.


  • Lambda Expressions -

No comments: