0% found this document useful (0 votes)
2 views

JDK 1.8 notes

The document outlines key changes in Java Development Kit (JDK) versions 1.7 and 1.8, including the introduction of 'try-with-resources' for automatic resource management, the ability to catch multiple exceptions in a single catch block, and the definition of static and default methods within interfaces. It also describes functional interfaces, lambda expressions, and the Consumer and Predicate interfaces, illustrating their usage with examples. The document emphasizes how these features enhance code efficiency and readability in Java programming.

Uploaded by

tstudent437
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JDK 1.8 notes

The document outlines key changes in Java Development Kit (JDK) versions 1.7 and 1.8, including the introduction of 'try-with-resources' for automatic resource management, the ability to catch multiple exceptions in a single catch block, and the definition of static and default methods within interfaces. It also describes functional interfaces, lambda expressions, and the Consumer and Predicate interfaces, illustrating their usage with examples. The document emphasizes how these features enhance code efficiency and readability in Java programming.

Uploaded by

tstudent437
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 51

Exception Changes in JDK 1.

7
__________________________________________________________________________
1. Try with resource bundle
___________________________________________________________________________
try with resource bundle means we pass object as parameter in try block called as try with resource.
Syntax:
try(object as parameter){
}
cach(exceptiontype ref){
}
2. Single reference using multiple exceptions.:
you can write more than one exception classes name as parameter in catch block and just we need to
separate it using pipe operator (|)

Syntax:
try(object as parameter){
}
cach(exceptiontype1 | exceptiontype2 | exceptiontype3 ref){
}

Example
package org.techhub;
import java.util.*;
public class TryCatchApplication {
public static void main(String[] args) {
try(Scanner xyz = new Scanner(System.in))
{
System.out.println("Enter two values");
int a=xyz.nextInt();
int b=xyz.nextInt();
int c=a/b;
System.out.println("Division is "+c);
}
catch(ArithmeticException | InputMismatchException | NumberFormatException ex) {
String s=(ex instanceof ArithmeticException)?"Arithmetic Exception is "+ex:
(ex instanceof InputMismatchException)?"Input Mismatch Exception is "+ex:"Number
format exception "+ex;
System.out.println(s);

}
}
}

JDK 1.8 version


____________________________________________________________________

1. Interface with method definition : from JDK 1.8 version of java we can define two types of method
within interface

a. static method : JDK 1.8 allow us to define static method within interface because static method can
call without object and interface cannot create its object but if we define static within interface you can
call it using interface name not compulsory to implement interface in any another class for static
method of interface

Example:
package org.techhub;
interface ABC{
static void show() {
System.out.println("I am show method of ABC");
}
}
public class InterfaceWithMethodDefination {

public static void main(String[] args) {


ABC.show();
}
}

JDK 8 provide default keyword to us which help us to define method within interface but if we use the
default method within interface you can call that method by implementer class object of interface
package org.techhub;
interface ABC{
default void show() {
System.out.println("I am show method of ABC");
}
}
class MNO implements ABC{

}
public class InterfaceWithMethodDefination {

public static void main(String[] args) {


MNO m = new MNO();
m.show();
}
}

Functional interface
______________________________________________________________________________
Functional interface means interface with single method called as functional interface.
means if we have interface which contain only one abstract method called as functional interface
Example Runnable is functional interface but if we want to restrict interface work as functional interface
we have annotation name as @FunctionalInterface

Example:
interface Test{
public void show();
}
If we think about above interface name as Test which contain method public void show() and Test
contain only one abstract method so it is a functional interface by default

Example:
interface Test{
public void show();
public void display();
}
If we think about above interface it contain two abstract method name as show() and display() so Test is
not functional interface.
So if we want to restrict Test interface work with single abstract method means if we want to restrict
Test as functional interface we have to use @FunctionalInterface annotation with test

@FunctionalInterface
interface Test{
public void show();
public void display();
}
Above code generate compile time error to us because we declare two abstract methods within
interface and mark with @Functioanlinterface but as per rule of FunctionalInterface cannot declare
more than one abstract so we get compile time error if we want to solve this declare only one abstract
method in interface shown in following code

package org.techhub;
@FunctionalInterface
interface Test{
public void show();

}
Note: you can more than one static method and default method within functional interface but only one
abstract method must be present
@FunctionalInterface
interface Test{
public void show();
static void a() {

}
static void b() {

}
default void c() {

Q. what is the purpose of functional interface in JAVA?


To work with Lambda expression

Before lambda expression we need to know anonymous inner class concept

Q. what is anonymous inner class?


_________________________________________________________________
Anonymous inner class means a class where we can create its object as well as can write its function
definition called as anonymous inner class.

Syntax:
classname ref = new classname(){
override here function
};
Note: The purpose of anonymous inner class is to use abstract class without inheritance as well as use
interface without implementation.

Example:
interface ABC{
void show();
}

Example;
package org.techhub;
interface ABC{
void show();
}
public class AnonymousTestApplication {
public static void main(String[] args) {
//anonymous inner class
ABC a1 = new ABC() {
@Override
public void show() {
System.out.println("I am interface method");
}
};
a1.show();
}
}

Example: we want to create thread using anonymous inner class


package org.techhub;

public class AnonymousTestApplication {


public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
try {
for(int i=1; i<=5; i++) {
System.out.println("I is "+i);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
};
t.start();
}
}
Example of thread using Runnable
package org.techhub;

public class AnonymousTestApplication {


public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hey i am thread");
}

};
Thread t = new Thread(r);
t.start();
}
}

Lambda expression: Lambda expression is short cut of anonymous inner class and the goal of lambda
expression is to optimize the code and avoid to write boilerplate code

Syntax of lambda expression


______________________________________________________________________
interfacename ref= (arguments)->{
write here your logics
};
Rules of lambda expression
1. Not need to write function name and its return type just mention the function bracket and
arguments.

Code without lambda expression


package org.techhub;

public class AnonymousTestApplication {


public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hey i am thread");
}

};
Thread t = new Thread(r);
t.start();
}
}

Code with lambda expression


package org.techhub;
public class AnonymousTestApplication {
public static void main(String[] args) {
Runnable r = ()->{
System.out.println("Hey i am thread");
};
Thread t = new Thread(r);
t.start();
}
}
2. not need to write opening and closing when we have single line statement with lambda
package org.techhub;

public class AnonymousTestApplication {


public static void main(String[] args) {
//lambda with single line of code
Runnable r = ()-> System.out.println("Hey i am thread");
Thread t = new Thread(r);
t.start();
}
}

3. not need to write throws close in lambda as well as not need to return keyword when single line

Note: Lambda can use with functional interfaces only

JDK functional interfaces


1. Consumer
2. Predicate
3. Function
4. Supplier
Consumer interface and forEach method
__________________________________________________________
Consumer interface is used for fetch data from collection using a forEach method
forEach() method introduce in JDK 1.8 and which is used for fetch data from collection

Syntax: default void forEach(Consumer<? super T> action);

Steps to work with forEach and consumer interface

If we want to use the consumer interface or any functional interface we have three ways.

1. By using implements keyword


2. By using anonymous inner class
3. By using lambda expression

Consumer interface use by using implements keyword


_________________________________________________________________

Example: we want to create ArrayList and store 5 values in it and fetch data using forEach method
package org.techhub;
import java.util.*;
import java.util.function.Consumer;
class MyConsum implements Consumer<Integer>{
@Override
public void accept(Integer t) {
System.out.println(t);
}
}
public class AnonymousTestApplication {
public static void main(String[] args) {

ArrayList<Integer> al =new ArrayList<Integer>();


al.add(10);
al.add(20);
al.add(40);
al.add(300);
al.add(400);
MyConsum m = new MyConsum();
al.forEach(m);
}
}
Consumer interface use by using anonymous inner class
_______________________________________________________________
package org.techhub;
import java.util.*;
import java.util.function.Consumer;

public class AnonymousTestApplication {


public static void main(String[] args) {

ArrayList<Integer> al =new ArrayList<Integer>();


al.add(10);
al.add(20);
al.add(40);
al.add(300);
al.add(400);
Consumer <Integer>c = new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.println(t);
}
};
al.forEach(c);
}
}
Use Consumer interface by using lambda expression
_________________________________________________________________________
package org.techhub;
import java.util.*;
import java.util.function.Consumer;

public class AnonymousTestApplication {


public static void main(String[] args) {

ArrayList<Integer> al =new ArrayList<Integer>();


al.add(10);
al.add(20);
al.add(40);
al.add(300);
al.add(400);
Consumer <Integer>c = (Integer t)->{
System.out.println(t);
};

al.forEach(c);
}
}
or
package org.techhub;
import java.util.*;
import java.util.function.Consumer;

public class AnonymousTestApplication {


public static void main(String[] args) {

ArrayList<Integer> al =new ArrayList<Integer>();


al.add(10);
al.add(20);
al.add(40);
al.add(300);
al.add(400);
Consumer <Integer>c = (Integer t)-> System.out.println(t);
al.forEach(c);
}
}
or
package org.techhub;
import java.util.*;
import java.util.function.Consumer;

public class AnonymousTestApplication {


public static void main(String[] args) {

ArrayList<Integer> al =new ArrayList<Integer>();


al.add(10);
al.add(20);
al.add(40);
al.add(300);
al.add(400);
al.forEach((Integer t)-> System.out.println(t));
}
}

Important points related with consumer interface


1. It is member of java.util.function package
2. it is Functional interface and it contain only one abstract method name as
public void accept(T t): it is generic parameter so you can customize it as per your requirement.

Example: we want to create collection and store 5 employee objects in it and display its data by using
Consumer interface
package org.techhub;

import java.util.*;
import java.util.function.Consumer;

class Employee {
private int id;
public Employee(String name,int id) {
this.name=name;
this.id=id;
}
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

private String name;

}
class FetchEmp implements Consumer<Employee>{

@Override
public void accept(Employee t) {
System.out.println(t.getId()+"\t"+t.getName());
}
}
public class AnonymousTestApplication {
public static void main(String[] args) {
ArrayList<Employee> al =new ArrayList<Employee>();
al.add(new Employee("ABC",1));
al.add(new Employee("MNO",2));
al.add(new Employee("PQR",3));
al.add(new Employee("STV",4));
al.add(new Employee("XYZ",5));
FetchEmp f = new FetchEmp();
al.forEach(f);

}
}
or
package org.techhub;

import java.util.*;
import java.util.function.Consumer;

class Employee {
private int id;
public Employee(String name,int id) {
this.name=name;
this.id=id;
}
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
private String name;

public class AnonymousTestApplication {


public static void main(String[] args) {
ArrayList<Employee> al =new ArrayList<Employee>();
al.add(new Employee("ABC",1));
al.add(new Employee("MNO",2));
al.add(new Employee("PQR",3));
al.add(new Employee("STV",4));
al.add(new Employee("XYZ",5));
Consumer <Employee>c = new Consumer<Employee>() {

@Override
public void accept(Employee t) {
System.out.println(t.getId()+"\t"+t.getName());
}

};
al.forEach(c);

}
}
or
package org.techhub;

import java.util.*;
import java.util.function.Consumer;

class Employee {
private int id;
public Employee(String name,int id) {
this.name=name;
this.id=id;
}
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

private String name;

public class AnonymousTestApplication {


public static void main(String[] args) {
ArrayList<Employee> al =new ArrayList<Employee>();
al.add(new Employee("ABC",1));
al.add(new Employee("MNO",2));
al.add(new Employee("PQR",3));
al.add(new Employee("STV",4));
al.add(new Employee("XYZ",5));
Consumer <Employee>c = (Employee t)->{
System.out.println(t.getId()+"\t"+t.getName());
};

al.forEach(c);

}
}
or
package org.techhub;

import java.util.*;
import java.util.function.Consumer;

class Employee {
private int id;
public Employee(String name,int id) {
this.name=name;
this.id=id;
}
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

private String name;

public class AnonymousTestApplication {


public static void main(String[] args) {
ArrayList<Employee> al =new ArrayList<Employee>();
al.add(new Employee("ABC",1));
al.add(new Employee("MNO",2));
al.add(new Employee("PQR",3));
al.add(new Employee("STV",4));
al.add(new Employee("XYZ",5));
Consumer <Employee>c = (Employee t)-> System.out.println(t.getId()+"\
t"+t.getName());
al.forEach(c);

}
}
or
package org.techhub;

import java.util.*;
import java.util.function.Consumer;

class Employee {
private int id;
public Employee(String name,int id) {
this.name=name;
this.id=id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class AnonymousTestApplication {
public static void main(String[] args) {
ArrayList<Employee> al =new ArrayList<Employee>();
al.add(new Employee("ABC",1));
al.add(new Employee("MNO",2));
al.add(new Employee("PQR",3));
al.add(new Employee("STV",4));
al.add(new Employee("XYZ",5));
al.forEach((Employee t)-> System.out.println(t.getId()+"\t"+t.getName()));
}
}
Predicate interface
__________________________________________________________________
Predicate is functional interface and which return Boolean value and normally we use Predicate
interface for check the conditions and contain method name as boolean test(Object)

Syntax:
boolean test(Object): this method help us to check the condition and if condition is true then
return true otherwise return false.

Example: WAP to check number is even or odd using Predicate interface


Note: we use Predicate interface by using Anonymous inner class.

Now we want to use Predicate interface by using Lambda expression

or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args) {
boolean b=((Predicate<Integer>)(Integer t)->t%2==0).test(10);
if(b) {
System.out.println("Number is even");
}
else {
System.out.println("Number is odd");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args) {
if(((Predicate<Integer>)(Integer t)->t%2==0).test(10)) {
System.out.println("Number is even");
}
else {
System.out.println("Number is odd");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args) {
String s=(((Predicate<Integer>)(Integer t)->t%2==0).test(10))?"Number is even":"Number is odd";
System.out.println(s);
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args) {
System.out.println((((Predicate<Integer>)(Integer t)->t%2==0).test(10))?"Number is even":"Number is
odd");
}
}
You can perform chaining of multiple conditions using Predicate interface.

Predicate and(Predicate): this method accept Predicate as parameter and return Predicate as result
Generally we can one predicate object is one condition

Example: WAP to compare the value between 1 to 10 if value between 1 to 10 returns true otherwise
return false.
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ Predicate <Integer> p1 = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return t>=1;
}
};
Predicate<Integer> p2 = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return t<=10;
}
};
Predicate<Integer> p3 = p2.and(p1);
boolean b= p3.test(4);
if(b) {
System.out.println("Number between 1 to 10");
}
else {
System.out.println("Number not between 1 to 10");
}
}
}
Convert above code using lambda expression
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ Predicate <Integer> p1 = (Integer t)->t>=1;
Predicate<Integer> p2 = (Integer t)->t<=10;
Predicate<Integer> p3 = p2.and(p1);
boolean b= p3.test(4);
if(b) {
System.out.println("Number between 1 to 10");
}
else {
System.out.println("Number not between 1 to 10");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ Predicate <Integer> p1 = (Integer t)->t>=1;
Predicate<Integer> p3 = ((Predicate<Integer>)(Integer t)->t<=10).and(p1);
boolean b= p3.test(4);
if(b) {
System.out.println("Number between 1 to 10");
}
else {
System.out.println("Number not between 1 to 10");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ Predicate<Integer> p3 = ((Predicate<Integer>)(Integer t)->t<=10).and((Integer t)->t>=1);
boolean b= p3.test(4);
if(b) {
System.out.println("Number between 1 to 10");
}
else {
System.out.println("Number not between 1 to 10");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ boolean b= ((Predicate<Integer>)(Integer t)->t<=10).and((Integer t)->t>=1).test(4);
if(b) {
System.out.println("Number between 1 to 10");
}
else {
System.out.println("Number not between 1 to 10");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ if(((Predicate<Integer>)(Integer t)->t<=10).and((Integer t)->t>=1).test(4)) {
System.out.println("Number between 1 to 10");
}
else {
System.out.println("Number not between 1 to 10");
}
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ String s=(((Predicate<Integer>)(Integer t)->t<=10).and((Integer t)->t>=1).test(4))?"Number
between 1 to 10":"Number not between 1 to 10";
System.out.println(s);
}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{ System.out.println((((Predicate<Integer>)(Integer t)->t<=10).and((Integer t)-
>t>=1).test(4))?"Number between 1 to 10":"Number not between 1 to 10");
}
}
or
WAP to input string and calculate its length and if length greater than 4 and less than 20 then show
message string is between 4 to 20

or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{
Predicate<String> p1 = new Predicate<String>() {
@Override
public boolean test(String t) {
return t.length()>=4;
}

};
Predicate<String>p2 = new Predicate<String>() {

@Override
public boolean test(String t) {
// TODO Auto-generated method stub
return t.length()<=20;
}

};
Predicate <String> p3 = p1.and(p2);
boolean b=p3.test("good morning");
String s=b?"String between 4 to 20":"string not between 4 and 20";
System.out.println(s);

}
}
Predicate using lambda expression
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{
Predicate<String> p1 = (String t)->t.length()>=4;
Predicate<String>p2 = (String t)->t.length()<=20;

Predicate <String> p3 = p1.and(p2);


boolean b=p3.test("good morning");
String s=b?"String between 4 to 20":"string not between 4 and 20";
System.out.println(s);

}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{
Predicate <String> p3 = ((Predicate<String>)(String t)->t.length()>=4).and((String t)-
>t.length()<=20);
boolean b=p3.test("good morning");
String s=b?"String between 4 to 20":"string not between 4 and 20";
System.out.println(s);

}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{
boolean b=((Predicate<String>)(String t)->t.length()>=4).and((String t)-
>t.length()<=20).test("good morning");
String s=b?"String between 4 to 20":"string not between 4 and 20";
System.out.println(s);

}
}
or
package org.techhub;
import java.util.function.Predicate;
public class PredicateApplication {
public static void main(String[] args)
{
String s=((Predicate<String>)(String t)->t.length()>=4).and((String t)->t.length()<=20).test("good
morning")?"String between 4 to 20":"string not between 4 and 20";
System.out.println(s);

}
}

Predicate interface with collection framework


______________________________________________________________________________
We want to create program to Create User class with username and its role and store 5 user class object
in ArrayList collection and Search using whose role is admin by using Predicate.
package org.techhub;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.*;
class User{
private String name;
public User(String name,String role) {
this.name=name;
this.role=role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
private String role;
}
public class PredicateApplication {
public static void main(String[] args)
{
ArrayList<User> al = new ArrayList<User>();
al.add(new User("Ram","User"));
al.add(new User("Shyam","User"));
al.add(new User("Ganesh","Admin"));
al.add(new User("Dinesh","User"));
al.add(new User("Sandeep","User"));
Predicate<String> p = new Predicate<String>() {

@Override
public boolean test(String t) {
// TODO Auto-generated method stub
return t.equals("Admin");
}

};
al.forEach( (User user)->{
if(p.test(user.getRole())) {
System.out.println(user.getName()+"\t"+user.getRole());
}
});

}
}
or
package org.techhub;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.*;
class User{
private String name;
public User(String name,String role) {
this.name=name;
this.role=role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
private String role;
}
public class PredicateApplication {
public static void main(String[] args)
{ ArrayList<User> al = new ArrayList<User>();
al.add(new User("Ram","User"));
al.add(new User("Shyam","User"));
al.add(new User("Ganesh","Admin"));
al.add(new User("Dinesh","User"));
al.add(new User("Sandeep","User"));
Predicate<String> p = (String t)->t.equals("Admin");
al.forEach( (User user)->{
if(p.test(user.getRole())) {
System.out.println(user.getName()+"\t"+user.getRole());
}
});
}
}
or
package org.techhub;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.*;
class User{
private String name;
public User(String name,String role) {
this.name=name;
this.role=role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
private String role;
}
public class PredicateApplication {
public static void main(String[] args)
{ ArrayList<User> al = new ArrayList<User>();
al.add(new User("Ram","User"));
al.add(new User("Shyam","User"));
al.add(new User("Ganesh","Admin"));
al.add(new User("Dinesh","User"));
al.add(new User("Sandeep","User"));
Predicate<String> p = (String t)->t.equals("Admin");
al.forEach( (User user)->{
if(((Predicate<String>)(String t)-
>t.equals("Admin")).test(user.getRole()))
System.out.println(user.getName()+"\t"+user.getRole());

});
}
}
or
package org.techhub;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.*;
class User{
private String name;
public User(String name,String role) {
this.name=name;
this.role=role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
private String role;
}
public class PredicateApplication {
public static void main(String[] args)
{
List<User> al=Arrays.asList(new User("Ram","User"),new User("Shyam","User"),new
User("Ganesh","Admin"),new User("Dinesh","User"),new User("Sandeep","User"));
al.forEach( (User user)->{
if(((Predicate<String>)(String t)-
>t.equals("Admin")).test(user.getRole()))
System.out.println(user.getName()+"\t"+user.getRole());
});
}
}

or
package org.techhub;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.*;
class User{
private String name;
public User(String name,String role) {
this.name=name;
this.role=role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
private String role;
}
public class PredicateApplication {
public static void main(String[] args)
{
Arrays.asList(new User("Ram","User"),new User("Shyam","User"),new User("Ganesh","Admin"),new
User("Dinesh","User"),new User("Sandeep","User")).forEach( (User user)->{ if(((Predicate<String>)
(String t)->t.equals("Admin")).test(user.getRole()))
System.out.println(user.getName()+"\t"+user.getRole());
});
}
}
Function interface
___________________________________________________________________
Function interface is part of JDK8 version of java which is used for accept input as parameter and return
some specified result so this is major function interface take 2 generic arguments namely as follow us.
T : T denote the Type of input argument
R: R denote the type of result return by function interface

There are four methods present in function interface


___________________________________________________________________________
1. apply() : this is only one abstract method present in Function interface using this method we can
achieve lambda expression and this method accept input as parameter and generate some result.

2. andThen(): this function can compose the result with apply result means if we use the andThen()
then this method first accept the result generated by apply() and after that perform operation on it.

3. compose(): this function can access the apply() input before process on it and after that apply() get
executed.
4. identity()

Example: we want to accept string as parameter and return its length using function interface.

Example using anonymous inner class


package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Function<String,Integer> f = new Function<String,Integer>(){
@Override
public Integer apply(String t) {

// TODO Auto-generated method stub


return t.length();
}

};

int result=f.apply("good");
System.out.println("Length of string is "+result);
}
}
Example using lambda expression
package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Function<String,Integer> f = (String t)->t.length();
int result=f.apply("good");
System.out.println("Length of string is "+result);
}
}
or
package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
int result=((Function<String,Integer>)(String t)->t.length()).apply("good");
System.out.println("Length of string is "+result);
}
}

Example: we want to input value and divide by 2 using a Function interface


package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Function<Double,Double> f = new Function<Double,Double>(){

@Override
public Double apply(Double t) {
// TODO Auto-generated method stub
return t/2.0;
}

};
Double result=f.apply(10.0);
System.out.println("Result is "+result);
}
}
or
package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
System.out.println("Result is "+((Function<Double,Double>)(Double t) ->t/2.0).apply(10.0));
}
}

Example: Divide number by 2 and get its result and multiply result by 3

Convert above example using lambda expressions


package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Function<Double,Double> f = (Double t)->t/2.0;
Function<Double,Double>f1=(Double t)->t*3.0;
Function <Double,Double>f2=f1.andThen();
Double result=f2.apply(10.0);
System.out.println("Result is "+result);
}
}
or

Example: WAP to pass 10 as parameter and multiply by 4 before divide by 2


package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Function<Double,Double> f = new Function<Double,Double>(){

@Override
public Double apply(Double t) {
// TODO Auto-generated method stub
return t/2.0;
}

};
Function<Double,Double> f1 = new Function<Double,Double>(){

@Override
public Double apply(Double t) {
// TODO Auto-generated method stub
return t*4.0;
}

};
Function <Double,Double>f2 = f1.compose(f);
Double result = f2.apply(13.0);
System.out.println("Result is "+result);

}
}
Convert above code using lambda expression
package org.techhub;
import java.util.function.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Function<Double,Double> f = (Double t)->t/2.0;
Function<Double,Double> f1 = (Double t)->t*4.0;
Function <Double,Double>f2 = f1.compose(f);
Double result = f2.apply(13.0);
System.out.println("Result is "+result);

}
}
or

Supplier interface: Supplier interface is used for return some result means this is functional interface
and not accept any input parameter just result some result it contain get() method which return always
some result.
Syntax: T get(): return some value

Example: WAP to display the current date of system


package org.techhub;
import java.util.function.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {

Supplier <Date>s= new Supplier<Date>() {

@Override
public Date get() {
return new Date();
}
};
Date result=s.get();
System.out.println("Today Date is "+result);
}
}
Convert above code in Lambda expression
package org.techhub;
import java.util.function.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {

Supplier <Date>s= ()->new Date();


Date result=s.get();
System.out.println("Today Date is "+result);
}
}

or
package org.techhub;
import java.util.function.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
System.out.println("Today Date is "+((Supplier<Date>)()->new Date()).get());
}
}

Stream API
__________________________________________________________________________
Stream API is very strong feature or updation in JDK 8 and which is used for minimize the boilerplate
code and reduce the code and improve the performance
If we want to work with Stream API we to know the following things
1. Collection Framework
2. Lambda expression
3. Functional interfaces like as Predicate, Function, Supplier etc

Introduction to Stream API


__________________________________________________________________________________
Stream API is related to collection framework or group of objects which help us to process on collection
or process on group of objects like as filter data from collection , perform map operation , perform
reduce operation on collection etc

Before start Stream API we want to implement one example without using Stream API with Collection

Example: We want to Create ArrayList and store 10 values in it and find the even number from ArrayList
and store in other collection means filter even number from collection

package org.techhub;
import java.util.function.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(1,4,6,9,11,14,53,23,22,33);
List<Integer> newList=new ArrayList<Integer>();
for(Integer val:list) {
if(val%2==0) {
newList.add(val);
}
}
System.out.println("display even numbers");
newList.forEach((value)->System.out.println(value));
}
}

Now we want to solve above by using Stream API and its filter() method

If we want to create reference of Stream interface we have method in collection name as stream() and
this method return reference of Stream interface and it is present in java.util.stream package.

Syntax: Stream ref = collref.stream();

If we want to filter data from collection using a specified condition we have filter() method of
Stream

Syntax: Stream filter(Predicate):

Example:
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(1,4,6,9,11,14,53,23,22,33);
Stream <Integer>stream1=list.stream();//created stream
Predicate<Integer> p = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return t%2==0;
}
};
Stream <Integer>stream2=stream1.filter(p);
}
}
once create reference of Stream object using filter() method using some Predication then you can
collect() result from stream and convert in to appropriate collection for that we have to call collect()
method of stream
Syntax: T collect(Collections.type): this method collect result generated by stream and convert in
specified type of collection
Example using simple anonymous inner class
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(1,4,6,9,11,14,53,23,22,33);
Stream <Integer>stream1=list.stream();//created stream
Predicate<Integer> p = new Predicate<Integer>() {

@Override
public boolean test(Integer t) {
return t%2==0;
}

};
Stream <Integer>stream2=stream1.filter(p);
List <Integer> resultList=stream2.collect(Collectors.toList());
Consumer<Integer> c = new Consumer<Integer>() {

@Override
public void accept(Integer t) {
System.out.println(t);
}

};
resultList.forEach(c);
}
}
or
Example using Lambda expression
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(1,4,6,9,11,14,53,23,22,33);
Stream <Integer>stream1=list.stream();//created stream
Predicate<Integer> p = (Integer t)->t%2==0;
Stream <Integer>stream2=stream1.filter(p);
List <Integer> resultList=stream2.collect(Collectors.toList());
Consumer<Integer> c = (Integer t)->System.out.println(t);
resultList.forEach(c);
}
}
or
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(1,4,6,9,11,14,53,23,22,33);
Stream <Integer>stream1=list.stream();//created stream
Stream <Integer>stream2=stream1.filter((Integer t)->t%2==0);
List <Integer> resultList=stream2.collect(Collectors.toList());
resultList.forEach((Integer t)->System.out.println(t));
}
}
or
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Arrays.asList(1,4,6,9,11,14,53,23,22,33).stream().filter((Integer t)->t%2==0).
collect(Collectors.toList()).forEach((Integer t)->System.out.println(t));
}
}

Example: WAP to create List and store 10 string or names in it and fine the name who ending with sh
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {

List<String>list=Arrays.asList("Ram","Ganesh","Shyam","dinesh","Sanket","Rajesh");
Stream<String> stream1=list.stream();
Predicate<String> p=new Predicate<String>() {
@Override
public boolean test(String t) {
return t.endsWith("sh");
}
};
Stream<String> stream2=stream1.filter(p);
List<String> resultList=stream2.collect(Collectors.toList());
Consumer <String> c = new Consumer<String>() {

@Override
public void accept(String t) {
System.out.println(t);
}

};
resultList.forEach(c);
}
}
or
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
List<String>list=Arrays.asList("Ram","Ganesh","Shyam","dinesh","Sanket","Rajesh");
Stream<String> stream1=list.stream();
Predicate<String> p=(String t)->t.endsWith("sh");
Stream<String> stream2=stream1.filter(p);
List<String> resultList=stream2.collect(Collectors.toList());
Consumer <String> c = (String t)->System.out.println(t);
resultList.forEach(c);
}
}
or
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Arrays.asList("Ram","Ganesh","Shyam","dinesh","Sanket","Rajesh").
stream().filter((String t)->t.endsWith("sh")).collect(Collectors.toList()).
forEach((String t)->System.out.println(t));
}
}

Example: Create Collection store 5 employee object in it and fine the employee whose salary is greater
than 10000

package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
class Employee{
private int id;
private String name;
public Employee(String name,int id,int sal) {
this.name=name;
this.id=id;
this.sal=sal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Employee emp1 = new Employee("ABC",1,6000);

List<Employee> list=Arrays.asList(new Employee("ABC",1,6000),new


Employee("MNO",2,12000),
new Employee("PQR",3,15000),new Employee("STV",4,7000));

Stream<Employee> stream1=list.stream();
Predicate<Employee> p = new Predicate<Employee>() {
@Override
public boolean test(Employee t) {

return t.getSal()>10000;
}
};
Stream<Employee> stream2=stream1.filter(p);
List<Employee> rList=stream2.collect(Collectors.toList());
Consumer<Employee> c= new Consumer<Employee>() {

@Override
public void accept(Employee t) {
System.out.println(t.getId()+"\t"+t.getName()+"\t"+t.getSal());

};
rList.forEach(c);

}
}
Convert above code using Lambda expression
package org.techhub;
import java.util.function.*;
import java.util.stream.*;
import java.util.*;
class Employee{
private int id;
private String name;
public Employee(String name,int id,int sal) {
this.name=name;
this.id=id;
this.sal=sal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
private int sal;
}
public class FunctionIterfaceApplication {
public static void main(String[] args) {
Arrays.asList(new Employee("ABC",1,6000),new Employee("MNO",2,12000),
new Employee("PQR",3,15000),new Employee("STV",4,7000)).stream().
filter((Employee t)->t.getSal()>10000).collect(Collectors.toList()).
forEach((Employee t)->System.out.println(t.getId()+"\t"+t.getName()+"\t"+t.getSal()));

}
}

map(): map() method is used for perform operation on every element in collection and stored in stream
object

package org.techhub;

import java.util.Arrays;
import java.util.*;
public class MapMethodTestApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(10,20,30,40,50);
ArrayList<Integer> newList=new ArrayList<Integer>();
for(Integer val:list) {
val=val*2;
newList.add(val);
}
System.out.println("After performing operation");
for(Integer val:newList) {
System.out.println(val);
}
}
}
if we think about above code we implement above code without using stream API and JDK 8 feature so
we want to implement above code using Stream and JDK 8

Example using anonymous inner classes


package org.techhub;

import java.util.Arrays;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class MapMethodTestApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(10,20,30,40,50);
Stream<Integer> stream1=list.stream();
Function<Integer,Integer> f=new Function<Integer,Integer>(){

@Override
public Integer apply(Integer t) {
// TODO Auto-generated method stub
return t*2;
}

};
Stream<Integer> stream2=stream1.map(f);
List<Integer> rList=stream2.collect(Collectors.toList());
Consumer<Integer> c=new Consumer<Integer>() {

@Override
public void accept(Integer t) {
// TODO Auto-generated method stub
System.out.println(t);
}

};
rList.forEach(c);
}
}
or
package org.techhub;
import java.util.Arrays;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class MapMethodTestApplication {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(10,20,30,40,50);
Stream<Integer> stream1=list.stream();
Function<Integer,Integer> f=(Integer t)->t*2;
Stream<Integer> stream2=stream1.map(f);
List<Integer> rList=stream2.collect(Collectors.toList());
Consumer<Integer> c=(Integer t)->System.out.println(t);
rList.forEach(c);
}
}
or
package org.techhub;
import java.util.Arrays;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
public class MapMethodTestApplication {
public static void main(String[] args) {
Arrays.asList(10,20,30,40,50).stream().map((Integer t)->t*2).
collect(Collectors.toList()).forEach((Integer t)->System.out.println(t));
}
}

reduce() function
_______________________________________________________________
reduce() function is used for process on collection element and generate the single value as result.

package org.techhub;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
Stream<Integer> s1 = list.stream();
int result = s1.reduce(0, new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer t, Integer u) {

return t + u;
}
});
System.out.printf("Sum of all value is %d\n", result);
}
}
or
package org.techhub;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
Stream<Integer> s1 = list.stream();
int result = s1.reduce(0, (Integer t, Integer u)->t + u);
System.out.printf("Sum of all value is %d\n", result);
}
}
or
package org.techhub;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static void main(String[] args) {
int result = Arrays.asList(10, 20, 30, 40, 50).stream().reduce(0, (Integer t, Integer u)->t + u);
System.out.printf("Sum of all value is %d\n", result);
}
}

Important points of Stream API


1. Stream is not a data structure alternatively it takes input from the Collection or Arrays or any IO
channels
2. Stream does not change an original data structure data like as cannot change collection or array just
stream provide result as pipelined methods
3. Each intermediate operation is lazily executed and returns a stream as result

You can Create Stream object by using a different ways

1. Using Collection
_______________________________________________________________-
package org.techhub;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static void main(String[] args) {

List<Integer> list=Arrays.asList(10,20,30,40,50);
Stream <Integer>stream1=list.stream();
/* Iterator<Integer> i=stream1.iterator();
while(i.hasNext()) {
Object value=i.next();
System.out.println(value);
}*/
stream1.forEach(System.out::println);
}
}

2. Create Stream object by using Stream.of() method


____________________________________________________________________________
package org.techhub;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static void main(String[] args) {
Stream<Integer> s1=Stream.of(10,20,30,40,50);
s1.forEach(System.out::println);
}
}

Create Stream object by using Array


package org.techhub;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static <T> void main(String[] args) {
int a[]=new int[] {10,20,30,40,50};
IntStream s1=Arrays.stream(a);
s1.forEach(System.out::println);
}
}
Create Stream object by using empty() method
_________________________________________________________________________
the empty() method is used to create empty stream for avoid initial values and null value.

Stream<Integer> s=Stream.empty();

Create Stream object by using Stream.builder() method


______________________________________________________________________
package org.techhub;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static <T> void main(String[] args) {
Stream.Builder<Integer> builder=Stream.builder();
Stream <Integer> s1=builder.add(10).add(20).add(30).add(40).add(50).build();
s1.forEach(System.out::println);
}
}

Create infinite stream


__________________________________________________________________________
Using iterate() method return infinite sequential ordered stream produced by iterative application of
function to an initial element called as seed element.

package org.techhub;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.*;
public class ReduceFunApplication {
public static <T> void main(String[] args) {
//Stream.iterate(2, (Integer n)->n*n).limit(5).forEach((value)->System.out.println(value));
//or
Stream <Integer> s1=Stream.iterate(2, (Integer n)->n*n);
Stream <Integer> s2=s1.limit(5);
s2.forEach(System.out::println);
}
}

Optional class in JDK 8


_________________________________________________________________________________
Optional class introduced in JDK 8 which helps to avoid or minimize the many check of null pointers.
Means NullPointerException occur at program run time and it is responsible for crash code so avoid this
problem we need to write multiple time try catch and handle NullPointerException or need to check the
for not null value many times in code so better way you can use Optional class provided by JDK 1.8 and it
is present java.util package

Methods of Optional class


_______________________________________________________________________
publc static Optional empty():return any empty optional object if there is no memory allocation for
reference
publc static Optional of(T value): Return an optional with specified present not nullable value.
public static Optional ofNullable(T value): return an Optional describing the specified value if non-null
otherwise return an empty optional

if we think about above code we create Array of reference of Employee class and we not created object
that references and we have statement Option<Employee>o =Optional.ofNullable(emp[0]) means we
pass null value to ofNullable() method and internally this method check reference value is null then
return empty optional object means Optional<Employee>o is empty optional object and we call method
o.isEmpty() this return true if reference value is null otherwise return false means when isEmpty()
method return true we consider there is NullPointerException otherwise not.

Instance method of Optional class


_____________________________________________________________________
boolean equals(Object): indicate wheather some other object equal to this optional
filter(Predicate): if value is present and this value matches given predicate return Optional describing
the value otherwise return empty optional.

Example:
package org.techhub;

import java.util.*;
import java.util.Optional;
import java.util.function.Predicate;
class Employee {
private int id;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}

private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

public class OptionalDemoApp {


public static void main(String[] args) {
Employee emp[] = new Employee[5];
for (int i = 0; i < emp.length; i++) {
Scanner xyz = new Scanner(System.in);
emp[i] = new Employee();
System.out.println("enter name and id of employee");
String name = xyz.nextLine();
int id = xyz.nextInt();
emp[i].setId(id);
emp[i].setName(name);
}
System.out.println("Display all employee");
Optional<Employee> o = null;
for (Employee e : emp) {
o = Optional.ofNullable(e);
if (!o.isEmpty()) {
o = o.filter((Employee t) -> t.getId() == 3);
if (o.isPresent()) {
e = o.get();
System.out.println(e.getId() + "\t" + e.getName());
}
}
}

}
}

public void ifPresent(Consumer): this method is used for fetch data of object whose value is not null.
package org.techhub;

import java.util.*;

public class OptionalDemoApp {


static int sum=0;
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, null, 40, 50);
list.forEach((value)->{
Optional<Integer> o = Optional.ofNullable(value);
Optional.ofNullable(value).ifPresent((value1)->{
sum=sum+value1;
});
});
System.out.println("Sum is "+sum);
}
}
or
package org.techhub;

import java.util.*;

public class OptionalDemoApp {


static int sum=0;
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, null, 40, 50);
list.forEach((value)->Optional.ofNullable(value).ifPresent((value1)->sum=sum+value1));
System.out.println("Sum is "+sum);
}
}
or
package org.techhub;

import java.util.*;

public class OptionalDemoApp {


static int sum=0;
public static void main(String[] args) {
Arrays.asList(10, 20, 30, null, 40, 50).forEach((value)-
>Optional.ofNullable(value).
ifPresent((value1)->sum=sum+value1));
System.out.println("Sum is "+sum);
}
}

You might also like