Java 8 features (Lambda expression, Functional Method, Method Reference, Default Method for interface, Streams & Many more..)


Java 8 is the most powerful & rich update to java till now after java 5. Some of features are Lambda expression, Functional Method, Method Reference, Default Method for interface, Streams for Java along with some update for existing like Date time API, New Java script engine Nashorn to use latest features, optional classes & encoder.

I will try to explain one by and will keep it updated time to time as and when required.


New Date Time API

As java.util.date was not threadsafe & localisation zone was not difficult to handle so introduced

java.time.* APIS 
enum chronounits in place of integer for date, day & month
toInstant() for backword compaitibilty


Defaults Methods
This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8. For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same


Functional Interface

Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method ‘compareTo’ is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions.Functional interface is interface having single method inside it.Some of them we have already in java without calling it as a functional interface.It is used heavily along with lambda expression introduced in java 8. Code on the right side of -> symbol is like a single method of functional interface (Thats why i say functional interface is target type for lambda expression). 

public interface Consumer<T>{
    void accept(T t)
}

its is being used in collection like below we have to pass functional interface as argument for collection for each method

void ForEach(Consumer<Integer> action){
      for(Integer i : Items) {
          action.accept(t)
    }
}



As per javadoc:
Functional interfaces provide target types for lambda expressions and method references. Each functional interface has a single abstract method, called the functional method for that functional interface, to which the lambda expression's parameter and return types are matched or adapted. Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context:

     // Assignment context
     Predicate<String> p = String::isEmpty;

     // Method invocation context
     stream.filter(e -> e.getSize() > 10)...

     // Cast context
     stream.map((ToIntFunction) e -> e.getSize())...





Lambda expression in Java 8

Lambda expression has been introduced for incorporating functional programming in java which was present in other language but not in java.
With help of lambda more compact code can be written & most of boiler plate can be reduced. Because of that code can be more cleaner.
Lambda can define anonymous functions , can be assigned to variables, can be passed to & returned from functions.Lambda is cool because you can use method like functionality without naming it or defining it. Think it as a inline define function or rich substitute of anonymous inner class.  

Example
Suppose we have a list of integers like 

List<Integers> integersList = Arrays.asList(1,2,3,4,5);

integersList.forEach(
    x -> System.out.println(x);   // lambda expression is defining a anonymous function which is taking a parameter x of type Integer.
);

Here above we got a list of integers which we want to print in most compact way.
forEach is a method that accept a function as a input & call it for each value in list.
default void forEach(Consumer<? super T> action) is a singnature of forEach interface deault method in java 8.

where Consumer is a functional interface having default implementation like 

public interface Consumer<T>{
    void accept(T t)
}

Functional interfaces provide target types for lambda expressions and method references.

In case of Map it can iterated with help of functional interface & lambda expression like

Map m<String, Integer> = new Hashmap<>();
m.put("A", 101);
m.put("B", 202);
m.put("C", 303);
m.put("D", 404);
m.put("E", 505);
m.put("F", 606);

m.forEach((k,v)->{System.out.println("Item : " + k + " Count : " + v);}
// lambda expression is defining a anonymous function which is taking a parameter k,v of type String & Integer.);

For understanding we can think lambda expression like static functions which is accepting argument from let of -> & having body if function is on right as below.

(arguments) -> {
    System.out.println("Item : " + k + " Count : " + v);
}


One more Example of Lambda expression is from collection is sorting.



List names = new ArrayList();
names.add("Ram");
names.add("Krishna");
names.add("vishnu");


/sort using java 8
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
// 2 arguments with lambda expressing using comparable functional interface implimetaion (which present in java earlier version but not as functional interface)
Output will be: Krishna, Ram, Vishnu



// if we sort using java 7
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}}



Method reference in Java 8


List names = new ArrayList();
names.add("Ram");
names.add("Krishna");
names.add("vishnu");
Java 8 style printing of collection
names.forEach(System.out::println);  // println method reference from System.out class.
Java 5 for each style printing of collection
for (Object s : names){
System.out.println(s); 
        };
    }
}

before java 5 normal style printing of collection
for (int i=0; i<names.size();i++ ){
System.out.println(names.get(i));
}

Output in each case: Ram, Krishna, Vishnu


Nashorn Java script engine

Nashorn is new JavaScript engine which comes with Java SE 8 which is replacing earlier Rhino. It has been launched to compete with latest JavaScript technologies. We can invoke as command line tool JJS.So basically inside java, jjs tool can interpret any javascript file directly & can provide output. It comes with many features like you can call java script functions directly from java code.You can also easily call java code or function directly from JavaScript as well.Types array, collections forEach , lambda expression and other features of java cane be used in JavaScript with help of Nashorn.


Optional class(java.util.Optional)

Java 8 has introduces optional class to avoid null pointer exception.Language like groovy already having a safe navigation operator represented by "?."  Its a object which may or may not contain Null value.
If a value is present, isPresent() will return true and get() will return the value.So with this class no need to check null since if you print or use anywhere if it is null no value become available. So if something is returning optional means it can be null.Just by reading signature of method we can understand that Null can be returned. Although i am not big fan of this feature since i feel it makes code less readable but still its a new feature a people can try out.



Streams
will update


Inbuilt encoder for Base 64 encoding
 will update


Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java