Java 8 Feature

Posted By : Prajesh Rai | 21-Aug-2018

Java 8 introduced several new Concept.
In this article, discussion will be based on the basic concept of the forEach method and Functional interface

 

1. The forEach method 

This method reduces the several lines of code and resolves the problem of concurrent modification exception when we perform some modification on collection object, the forEach method also remove the looping concept which  used to be there in the previous version of java.
In the previous version of Java, we used to display the value of the list by using forEach loop or by using iterator


public class 
{
public static void main(String[]args){
List<Integer>list=Arrays.asList(1,2,3,4,5,6);
for(List arrayList:list){
System.out.println(arrayList);
 }
}
}

or

public class
{
public static void main(String[]args)
{
List<Integer>list=Arrays.asList(1,2,3,4,5,6);
Iterator<Integer>itr=list.iterator();
while(itr.hasNext())
{
Integer i=itr.next();
System.out.println(i);
}
}
}


Now in Java 8, we use the forEach method to iterate the object of collection.

public class 
{
public static void main(String[]args){
List<Integer>list=Arrays.asList(1,2,3,4,5,6);
 list.forEach(i->System.out.println(i));
}

}

2.Function Interface
  The function Interface is an interface which contains only a single abstract method.
  In Java 8 we also use static and default method inside the java interface and also provide the body of it.
  Example of the Function interface.

@FunctionalInterface
interface Example
{
void show();
default void display()
{
System.out.println("display");
}
static void watch(){
System.out.println("watch"); 
}
}
class Expression
{
public static void main(String[]args)
{
Example example;
example=()->System.out.println("Show");
example.show();
example.display();
Example.watch();
}
}

 

In this example, I use inner class and a lambda expression to implement the interface and its abstract method.
In the previous version of java, we need to make a class which implements the interface and then create the object of the implemented class to call the interface overridden method, but Java 8 provides the feature of lambda expression and inner class which has reduced the unnecessary code.   

About Author

Author Image
Prajesh Rai

Prajesh Rai is a Java Developer. Currently, he is working on Spring-boot. He always interested to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..