Skip to main content

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 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) {

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 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.  

Suppose we have a list of integers like 

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

    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();

/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>() {
public int compare(String s1, String s2) {
return s1.compareTo(s2);

Method reference in Java 8

List names = new ArrayList();
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){

before java 5 normal style printing of collection
for (int i=0; i<names.size();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.

will update

Inbuilt encoder for Base 64 encoding
 will update


Popular posts from this blog

Conversion from Clob To String in java and Vice versa

/***reading Clob data from oracle table and setting to Pojo**/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import oracle.sql.CLOB;


public class MessageDao {
private static String url = "jdbc:oracle:thin:@";
private static String username = "ABC123";
private static String password = "ABC123";

public  List readClobToBO() throws Exception {

Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn
ResultSet resultSet = stmt.executeQuery();
List msgList= new ArrayList();

while ( {

StagedMessage message = new StagedMessage();


Portable Java 8/ JDK8 setup without admin rights

Some time we got machine to work where we don't have access rights to install anything or if you do not want to install. You can get latest jdk running by this trick. Just follow step step & do comment if you like it.

Step by Step details to get running java from .exe setup without any admin rights. Get portable 7 zip from portableapps.comdownload java 8 from oracle 7 zip & extract jdk-8u102-windows-x64.exeyou will see below folders                .data                .pdata                .rdata                .reloc                .rsrc                .text                CERTIFICATE

          5.Go inside E:\jdk-8u102-windows-x64\.rsrc\1033\JAVA_CAB10you will find 111 file.

         6.extract it it some folder where you can find again extract that to some folder say Java & copy it to very first folder of setup along with .data,.rsrc etc.
         7.Go to folder where you have co…

GOF Design pattern with Java & Real World Examples

What are design patterns? 

So basically these are just collection of best practices to solve recurring problem by different kind of class arrangement. These arrangement could be based on creation of object or structural basis or on basis of required behavior.

Creational Design Pattern
Prototype Designpattern we will like to use this designpattern whenever creation of initial object & setting required default values is costly. So we just create 1 object & later on whenever more objects required we can provide initial object by just cloning of given object.Java Example is java.lang.Object#clone()
Builder DesignPattern When we jave object structure are complex and complicated we would go for this. we will be separating object creation from internal representation. With help of some simple interface we would create complicated Object.
Singleton When we need one instance per JVM. Example : Java Run time environment Java.lang.System.  java.lang.StringBuilder, Spring Beans are singleton …