Monday, February 23, 2015

JAVA8 Lambda part1


Lambda expressions are a new and important feature included in Java SE 8. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. In addition, new concurrency features improve performance.

Lambda Expression Syntax
(Arguments)      (Arrow Token)  (Body)
(int x,int y)        ->    x+y

Arguments:
argument list is like normal method level parameters list, it can be no argument also. i.e.

() -> 121


it will return 121 value and no argument list.

Body:
body can be statement block or logical block with return statement.

more samples :

(String s) -> { System.out.println(s); }


block form just print the string.

a lambda could be represented as a comma-separated list of parameters, the –> symbol and the body. For example:

Arrays.asList( "Item1", "Item2", "Item3" ).forEach( e -> System.out.println( e ) );


Please notice the type of argument e is being inferred by the compiler. Alternatively, you may explicitly provide the type of the parameter.

Arrays.asList("Item1", "Item2", "Item3").forEach((String e) -> System.out.println(e));


If expression/processing in complex then add the brackets i.e.

Arrays.asList("Item1", "Item2", "Item3").forEach(e -> {
            System.out.print(e);
        });

String separator = ",";
Arrays.asList( "Item1", "Item2", "Item3" ).forEach( {
    ( String e ) -> System.out.print( e + separator ) });

lambda expression will return the value as well. i.e.

Arrays.asList( "Item1", "Item2", "Item3" ).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );

 Arrays.asList( "Item1", "Item2", "Item3" ).sort( ( e1, e2 ) -> {
    int result = e1.compareTo( e2 );
    return result;
} );

Functional Interfaces:

a Functional Interface is an interface with just one abstract method declared in it.

java.lang.Runnable is an example of a Functional Interface. There is only one method void run() declared in Runnable interface. We use Anonymous inner classes to instantiate objects of functional interface. With Lambda expressions.

// Anonymous Runnable
     Runnable r = new Runnable(){
       
       @Override
       public void run(){
         System.out.println("Hello world old!");
      }

    };

// Lambda Runnable
     Runnable r = () -> System.out.println("Hello world new!");

Comparator Lambda expression



traditional compator sort
</hr>
Collections.sort(list, new Comparator<Person>() {
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName());
            }
        });

Lambda sort 
</hr>
Collections.sort(list, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));
full sample





references
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html


Reactions: