22.java 8 New Features
22.java 8 New Features
Java 10 - 2018
1) Lambda Expression
2) FunctionalInterfaces
3) Default methods
4) Predicates
5) Functions
6) Double colon operator(::)
7) Stream API
8) Date and Time API
Etc…..
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
174 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) If multiple parameters present then these parameters should be separated with comma(,).
4) If zero number of parameters available then we have to use empty parameter [ like ()].
Ex:
() sop(“hello”);
5) If only one parameter is available and if the compiler can expect the type then we can remove the
type and parenthesis also.
Ex: 1 () { A sop(a);
public void m1() { sop(“hello”); 6) Similar to method body lambda expression body also can contain multiple statements.if more
sop(“hello”); } than one statements present then we have to enclose inside within curly braces.if one statement
} () { sop(“hello”); } present then curly braces are optional.
() sop(“hello”);
Ex:2 7) Once we write lambda expression we can call that expression just like a method, for this
public void add(inta, int b) { functional interfaces are required.
sop(a+b); (inta, int b) sop(a+b);
} Functional Interfaces:
If the type of the parameter can be decided by compiler automatically based on the context then if an interface contain only one abstract method, such type of interfaces are called functional
we can remove types also. interfaces and the method is called functional method or single abstract method(SAM).
The above Lambda expression we can rewrite as (a,b) sop (a+b); Ex:
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
175 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
176 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
In the child interface we can’t define any new abstract methods otherwise child interface won’t be
FunctionalInterface and if we are trying to use @FunctionalInterface annotation then compiler gives
an error message.
Ex:
@FunctionalInterface {
public void m1(); this code gives compilation error.
public void m2();
}
Inside FunctionalInterface we have to take exactly only one abstract method.If we are not declaring
that abstract method then compiler gives an error message.
Ex:
@FunctionalInterface {
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
177 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
178 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
In the above example in both parent & child interface we can write any number of default methods Without Lambda Expression
and there are no restrictions.Restrictions are applicable only for abstract methods.
1) interface Interf {
FunctionalInterface Vs Lambda Expressions: 2) public void sum(inta,int b);
3) }
Once we write Lambda expressions to invoke it’s functionality, then FunctionalInterface is required. 4) class Demo implements Interf {
We can use FunctionalInterface reference to refer Lambda Expression. 5) public void sum(inta,int b) {
Where ever FunctionalInterface concept is applicable there we can use Lambda Expressions 6) System.out.println(“The sum:” +(a+b));
Ex:1 7) }
Without Lambda Expression 8) }
9) public class Test {
1) interface Interf { 10) public static void main(String[] args) {
2) public void methodOne() {} 11) Interfi = new Demo();
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
179 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
180 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
181 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
182 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
☀ Hence if anonymous inner class implements functionalinterface in that particular case only we can 15) Test t = new Test();
replace with lambda expressions.hence wherever anonymous inner class concept is there,it may 16) t.m2();
not possible to replace with Lambda expressions. 17) }
18) }
☀ Anonymous inner class! = Lambda Expression
☀ From lambda expression we can access enclosing class variables and enclosing method variables
☀ Inside anonymous inner class we can declare instance variables.
directly.
☀ Inside anonymous inner class “this” always refers current inner class object(anonymous inner
☀ The local variables referenced from lambda expression are implicitly final and hence we can’t
class) but not related outer class object
perform re-assignment for those local variables otherwise we get compile time error
Ex:
Ex:
1) interface Interf {
2) public void m1();
3) }
4) class Test {
5) int x = 10;
6) public void m2() {
7) int y = 20;
Ex: 8) Interfi = () {
9) System.out.println(x); 10
1) interface Interf { 10) System.out.println(y); 20
2) public void m1(); 11) x = 888;
3) } 12) y = 999; //CE
4) class Test { 13) };
5) int x = 777; 14) i.m1();
6) public void m2() { 15) y = 777;
7) Interfi = () { 16) }
8) int x = 888; 17) public static void main(String[] args) {
9) System.out.println(x); 888 18) Test t = new Test();
10) System.out.println(this.x); 777 19) t.m2();
11) }; 20) }
12) i.m1(); 21) }
13) }
14) public static void main(String[] args) {
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
185 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
186 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Differences between anonymous inner classes and Lambda expression ☀ Every variable declared inside interface is always public static final whether we are declaring or
not.
Anonymous Inner class Lambda Expression ☀ But from 1.8 version onwards in addition to these, we can declare default concrete methods also
It’s a class without name It’s a method without name(anonymous function) inside interface,which are also known as defender methods.
Anonymous inner class can extend lambda expression can’t extend
Abstract and concreateclasses Abstract and concreate classes ☀ We can declare default method with the keyword “default” as follows
Anonymous inner class can implement lambda expression can implement an
An interface that contains any number of Interface which contains single abstract method 1) default void m1(){
Abstract methods (FunctionalInterface) 2) System.out.println (“Default Method”);
Inside anonymous inner class we can Inside lambda expression we can’t 3) }
Declare instance variables. Declare instance variables,whater the variables
declare are simply acts as local variables.
Anonymous inner classes can be lambda expressions can’t be instantiated Interface default methods are by-default available to all implementation classes.Based on
Instantiated requirement implementation class can use these default methods directly or can override.
Inside anonymous inner class “this” Inside lambda expression “this”
Always refers current anonymous Always refers current outer class object.that is Ex:
Inner class object but not outer class enclosing class object.
Object. 1) interface Interf {
2) default void m1() {
Anonymous inner class is the best choice Lambda expression is the best Choice if we want
3) System.out.println("Default Method");
If we want to handle multiple methods. to handle interface
4) }
With single abstract method (FuntionalInterface).
5) }
In the case of anonymous inner class At the time of compilation no dot Class file will be 6) class Test implements Interf {
At the time of compilation a separate generated for Lambda expression.it simply 7) public static void main(String[] args) {
Dot class file will be generated convert in to private method outer class. 8) Test t = new Test();
(outerclass$1.class) 9) t.m1();
Memory allocated on demand Reside in permanent memory of JVM 10) }
Whenever we are creating an object (Method Area). 11) }
Note:
We can’t override object class methods as default methods inside interface otherwise we get
compiletime error.
Ex:
1) interface Interf {
2) default inthashCode() {
3) return 10;
Default methods 4) }
☀ Until 1.7 version onwards inside interface we can take only public abstract methods and public 5) }
static final variables(every method present inside interface is always public and abstract whether
we are declaring or not). CompileTimeError
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
187 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
188 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
interfacename.super.m1();
Reason: object class methods are by-default available to every java class hence it’s not required to
bring through default methods. Ex:
Ex:1
1) interface Interf {
2) public static void m1() {}
3) }
4) class Test implements Interf {
5) public static void m1() {}
6) }
Ex:2
1) interface Interf {
2) public static void m1() {}
3) }
4) class Test implements Interf {
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
191 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
192 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
2) class Test {
Predicates 3) public static void main(String[] args) {
4) predicate<Integer> p = I (i>10);
A predicate is a function with a single argument and returns boolean value. 5) System.out.println(p.test(100));
To implement predicate functions injava,oracle people introduced Predicate interface in 1.8 6) System.out.println(p.test(7));
version(i.e.,Predicate<T>). 7) System.out.println(p.test(true)); //CE
Predicate interface present in java.util.function package. 8) }
It’s a functional interface and it contains only one method i.e., test() 9) }
Ex: # 1 Write a predicate to check the length of given string is greater than 3 or not.
interface Predicate<T> { Predicate<String> p = s (s.length() > 3);
public boolean test(T t); System.out.println (p.test(“rvkb”)); true
} System.out.println (p.test(“rk”)); false
As predicate is a functional interface and hence it can refers lambda expression
#-2 write a predicate to check whether the given collection is empty or not.
Ex:1 Predicate<collection> p = c c.isEmpty();
Write a predicate to check whether the given integer is greater than 10 or not.
Predicate joining
Ex: It’s possible to join predicates into a single predicate by using the following methods.
public boolean test(Integer I) { and()
if (I >10) { or()
return true; negate()
} these are exactly same as logical AND ,OR complement operators
else {
return false;
}
}
Predicate can return only Function can return any type of value
Function boolean value.
Functions are exactly same as predicates except that functions can return any type of result but
function should(can)return only one value and that value can be any type as per our requirement. Note:
To implement functions oracle people introduced Function interface in 1.8version. Predicate is a boolean valued function
Function interface present in java.util.function package. and(), or(), negate() are default methods present inside Predicate interface.
Functional interface contains only one method i.e., apply()
interface function(T,R) {
public R apply(T t);
}
Assignment:
Write a function to find length of given input string.
Ex:
1) import java.util.function.*;
2) class Test {
3) public static void main(String[] args) {
4) Function<String, Integer> f = s ->s.length();
5) System.out.println(f.apply("Durga"));
6) System.out.println(f.apply("Soft"));
7) } Method and Constructor references by using ::(double colon)operator
8) }
functionalInterface method can be mapped to our specified method by using :: (double
colon)operator. This is called method reference.
Note:
Function is a functional interface and hence it can refer lambda expression. Our specified method can be either static method or instance method.
FunctionalInterface method and our specified method should have same argument types ,except this
the remaining things like
returntype,methodname,modifiersetc are not required to match.
Syntax:
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
195 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
196 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
In the above example Runnable interface run() method referring to Test class static method m1().
Method reference to Instance method:
Ex:
1) interface Interf {
2) public void m1(int i);
3) }
4) class Test {
5) public void m2(int i) {
6) System.out.println("From Method Reference:"+i);
Ex: With Lambda Expression 7) }
8) public static void main(String[] args) {
9) Interf f = I ->sop("From Lambda Expression:"+i);
1) class Test { 10) f.m1(10);
2) public static void main(String[] args) { 11) Test t = new Test();
3) Runnable r = () { 12) Interf i1 = t::m2;
4) for(int i=0; i<=10; i++) { 13) i1.m1(20);
5) System.out.println("Child Thread"); 14) }
6) } 15) }
7) };
8) Thread t = new Thread(r); In the above example functional interface method m1() referring to Test class instance method m2().
9) t.start(); The main advantage of method reference is we can use already existing code to implement functional
10) for(int i=0; i<=10; i++) { interfaces(code reusability).
11) System.out.println("Main Thread");
12) } Constructor References
13) } We can use :: ( double colon )operator to refer constructors also
14) }
Syntax: classname :: new
With Method Reference
Ex:
Interf f = sample :: new;
1) class Test { functional interface f referring sample class constructor
2) public static void m1() {
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
197 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
198 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
file. i.e it represents stream of binary data or character data from the file .hence java.io streams and
Ex: java.util streams both are different.
Ex:
Stream s = c.stream();
Note: 1.configuration
In method and constructor references compulsory the argument types must be matched. 2.processing
Streams configuration:
we can configure either by using filter mechanism or by using map mechanism.
To process objects of the collection, in 1.8 version Streams concept introduced.
Filtering:
What is the differences between java.util.streams and java.io streams? we can configure a filter to filter elements from the collection based on some boolean condition by
using filter()method of Stream interface.
java.util streams meant for processing objects from the collection. Ie, it represents a stream of objects
from the collection but java.io streams meant for processing binary and character data with respect to public Stream filter(Predicate<T> t)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
199 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
200 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
Ex:
Stream s = c.stream();
Stream s1 = s.map(i-> i+10);
Once we performed configuration we can process objects by using several methods.
12) } the sorting can either default natural sorting order or customized sorting order specified by
13) } comparator.
sorted()- default natural sorting order
Ex: Program for map() and collect() Method sorted(Comparator c)-customized sorting order.
Ex:
1) import java.util.*; List<String> l3=l.stream().sorted().collect(Collectors.toList());
2) import java.util.stream.*; sop(“according to default natural sorting order:”+l3);
3) class Test {
4) public static void main(String[] args) { List<String> l4=l.stream().sorted((s1,s2) -> -s1.compareTo(s2)).collect(Collectors.toList());
5) ArrayList<String> l = new ArrayList<String>(); sop(“according to customized sorting order:”+l4);
6) l.add("rvk"); l.add("rk"); l.add("rkv"); l.add("rvki"); l.add("rvkir");
7) System.out.println(l); IV.Processing by min() and max() methods
8) List<String> l2 = l.Stream().map(s ->s.toUpperCase()).collect(Collectors.toList());
9) System.out.println(l2); min(Comparator c)
10) } returns minimum value according to specified comparator.
11) }
max(Comparator c)
returns maximum value according to specified comparator
Ex:
String min=l.stream().min((s1,s2) -> s1.compareTo(s2)).get();
sop(“minimum value is:”+min);
V.forEach() method
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
203 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
204 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
JAVA Means DURGA SIR JAVA Means DURGA SIR
O/p:
2015-11-23
12:39:26:587
VI.toArray() method
we can use toArray() method to copy elements present in the stream into specified array
we can also apply a stream for group of values and for arrays. 1) import java.time.*;
2) class Test {
Ex: 3) public static void main(String[] args) {
Stream s=Stream.of(99,999,9999,99999); 4) LocalDate date = LocalDate.now();
s.forEach(System.out:: println); 5) System.out.println(date);
6) int dd = date.getDayOfMonth();
7) int mm = date.getMonthValue();
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
205 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
206 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Once we get LocalTime object we can call the following methods on that object. We can create ZoneId for a particular zone as follows
Ex: Ex:
ZoneId la = ZoneId.of("America/Los_Angeles");
1) importjava.time.*; ZonedDateTimezt = ZonedDateTime.now(la);
2) class Test { System.out.println(zt);
3) public static void main(String[] args) {
4) LocalTime time = LocalTime.now();
5) int h = time.getHour(); Period Object:
6) int m = time.getMinute(); Period object can be used to represent quantity of time
7) int s = time.getSecond(); Ex:
8) int n = time.getNano(); LocalDate today = LocalDate.now();
9) System.out.printf("\n%d:%d:%d:%d",h,m,s,n); LocalDate birthday = LocalDate.of(1989,06,15);
10) } Period p = Period.between(birthday,today);
11) } System.out.printf("age is %d year %d months %d days",p.getYears(),p.getMonths(),p.getDays());
If we want to represent both Date and Time then we should go for LocalDateTime object. # write a program to check the given year is leap year or not.
Ex:
LocalDateTime dt1=LocalDateTime.of(1995,04,28,12,45);
sop(dt1);
To Represent Zone:
ZoneId object can be used to represent Zone.
Ex:
1) import java.time.*;
2) class ProgramOne {
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
207 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
208 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com