Java 8 - Lambda & Functional Interfaces
Java
8 supposted to be a major release after Java 5 and it brought a lot
of new changes and ease for java developers i.e.
language,compiler,libraries,tools and runtime (JVM)
Lambdas
and Functional Interfaces
Lambdas
allow
us to treat functionality as a method argument (passing functions
around), or treat a code as data. So,
this is must be good news for functional developers and from now on
no need for anonymous classes in order to do functional programming
with java.
Examples
(->
lambda):
-
Arrays.asList(“a”,”b”,”c”,”d”).forEach( e -> System.out.println( e ) );
-
Arrays.asList(“a”,”b”,”c”,”d”).forEach( ( String str ) -> System.out.println( str ) );
-
Arrays.asList(“a”,”b”,”c”,”d”).forEach( ( String str ) -> {
System.out.println( str ) ;
System.out.println( str + ”,”) ;
} );
Obviously
lambda expression returns a value to but, it must not need to be
declared, if not required.
-
Arrays.asList(“a”,”b”,”c”,”d”).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );
OR
-
Arrays.asList(“a”,”b”,”c”,”d”).sort( ( e1, e2 ) ->
{
int result = e1.compareTo( e2 );
return result;
});
Interface’s Default and Static Methods
Two
new concepts of methods in interface; default
and static methods.
Default
method, make
interfaces somewhat similar to traits but serve a bit different goal.
They allow adding new methods to existing interfaces without breaking
the binary compatibility with the code written for older versions of
those interfaces.
The
difference between default methods and abstract methods is that
abstract methods are required to be implemented.
Example:
private interface Defaultable{
//
Interfaces now allow default methods, the implementer may or
//
may not implement (override) them.
default
String notRequired(){
return
“Default Implementation”;
}
}
private static class DefaultableImpl implements Defaultable{
}
private static class OverridableImpl implements Defaultable{
@Override
public static String notRequired(){
return “New Implementation”;
}
}
In
java 8 interface can declare and implement static methods too:
private interface DefaultableFactory{
//a new static method’s
static Defaultable create(Supplier<Defaultable> supplier){
return supplier.get();
}
}
The
small code snippet below glues together the default methods and
static methods from the examples above.
public static void main(String[] args){
Defaultable defaultable = DefaultableFactory.create(DefaulatableImpl::new);
System.out.print(defaultable.notRequired());
defaultable = DefaultableFactory.create( OverridableImpl::new);
System.out.print(defaultable.notRequired());
}
Default
methods implementation on JVM is very efficient and is supported by
the byte code instructions for method invocation. Default methods
allowed existing Java interfaces to evolve without breaking the
compilation process. The good examples are
java.util.Collection interface:stream(),parallelStream(),forEach() and etc.
Comments
Post a Comment