JDK 1.8 notes
JDK 1.8 notes
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);
}
}
}
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 {
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 {
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() {
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();
}
}
};
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
};
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
If we want to use the consumer interface or any functional interface we have three ways.
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) {
al.forEach(c);
}
}
or
package org.techhub;
import java.util.*;
import java.util.function.Consumer;
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;
}
}
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;
}
@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;
}
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;
}
}
}
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.
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;
}
}
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);
}
}
@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
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.
};
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);
}
}
@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
@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
@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) {
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
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.
If we want to filter data from collection using a specified condition we have filter() method of
Stream
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);
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
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);
}
}
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);
}
}
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();
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);
}
}
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.
Example:
package org.techhub;
import java.util.*;
import java.util.Optional;
import java.util.function.Predicate;
class Employee {
private int id;
}
}
public void ifPresent(Consumer): this method is used for fetch data of object whose value is not null.
package org.techhub;
import java.util.*;
import java.util.*;
import java.util.*;