Java - 8 Features
Java - 8 Features
Lambda Expressions:
It is very important feature added in java 8.
Java doesn’t support functional programming up to
java 7, but from java 8 onwards java is also supports
functional interface.
It is best suitable for providing implementation for
Single abstract method interface/functional
interface/one method interface.
It will provide implementation for functional
interface in the very short format and clear manner.
It is best suitable for collection framework library.
It is the best suitable for navigating/iterating,
filtering and read or extract the data from collection
objects.
Before talk about Lambda expression first we must
and should be aware about Functional Interface.
An interface which contains exactly only one
abstract method is called Functional Interface or Single
abstract method interface or single/one method
interface.
To represents an interface as Functional Interface,
we have one annotation like @FunctionalInterface.
interface Test{
public abstract void m1();
}
class Check implements Test{
@Override
public void m1() {
System.out.println("This is
implementation method for Test
interface.....");
}
}
public class Lambda {
public static void main(String[] s) {
Test t = new Check();
t.m1();
}
}
interface Test{
public abstract void m1();
}
interface Test{
public abstract void m1();
public abstract void m2();
}
interface Test{
public abstract void m1();
}
public class Lambda {
public static void main(String[] s) {
Test t = () -> {
System.out.println("this is
implementation for Test interface"
+ " by using lamda");
};
t.m1();
}
}
interface Square{
public static final int side=50;
public abstract void area();
}
public class Lambda {
public static void main(String[] s) {
Square t = new Square() {
public void area() {
System.out.println("The area of the
square is:: "+(4*side));
}
};
t.area();
}
}
interface Square{
public static final int side=50;
public abstract void area();
}
public class Lambda {
public static void main(String[] s) {
Square t =() -> {
System.out.println("The area of the
square is:: "+(4*side));
};
t.area();
}
}
We will get compile time error. That is can’t find
symbol variable side.
In the above side variable is not taking from the Square
interface the reason lambda is not an implementation
class of Square. It is a just function.
To overcome the above problem, take one local “side”
variable in main method like bellow.
interface Square{
public abstract void area();
}
public class Lambda {
public static void main(String[] s) {
int side=500;
Square t =() -> {
System.out.println("The area of the
square is:: "+(4*side));
};
t.area();
}
}
We can take “side” variable as static at class level like
bellow.
interface Square{
public abstract void area();
}
public class Lambda {
static int side=14;
public static void main(String[] s) {
Square t =() -> {
System.out.println("The area of the
square is:: "+(4*side));
};
t.area();
}
}
But don’t take “side” variable as non-static/instance
the reason is non-static data we can’t call directly from
static context.
interface Square{
public abstract void area();
}
public class Lambda {
int side=14;
public static void main(String[] s) {
Square t =() -> {
System.out.println("The area of the
square is:: "+(4*side));
};
t.area();
}
}
Compile Time Error: non-static variable cannot be
referenced from static context.
Program on Lambda Expression of Functional interface
which contains argument method.
interface Square{
public abstract void area(int side);
}
public class Lambda {
public static void main(String[] s) {
Square t = (side) -> {
System.out.println("The area of the square
is:: "+(4*side));
};
t.area (111);
}
}
Program on Lambda Expression of Functional interface
which contains argument method.
interface Rectangle{
public abstract void area(int length, int
breadth);
}
public class Lambda {
public static void main(String[] s) {
Rectangle t =(a,b) -> {
System.out.println("The area of the square
is:: "+(a*b));
};
t.area(10,20);
}
}
interface Rectangle{
public abstract int area(int length, int
breadth);
}
public class Lambda {
public static void main(String[] s) {
Rectangle t =(a,b) -> {
return a*b;
};
System.out.println(t.area(100,200));
Rectangle t1 =(a,b)->(2*(a+b));
System.out.println(t1.area(10,20));
}
}
In the last but one line don’t try to write body like
bellow.
Rectangle t1 = (a, b) ->{(2*(a+b))};
(Or)
Rectangle t1 = (a, b) ->{(2*(a+b));};
import oracle.net.aso.e;
class Student{
int sid;
String sname;
Integer sage;
public Student(int sid, String sname, int sage) {
super();
this.sid = sid;
this.sname = sname;
this.sage = sage;
}
@Override
public String toString() {
return sid+"..."+sname+"..."+sage;
}
}
public class Lambda {
public static void main(String[] args) {
Student s1 = new Student(101,"ram",30);
Student s2 = new Student(102,"sam",20);
Student s3 = new Student(103,"varun",40);
Student s4 = new Student(104,"kiran",50);
Student s5 = new Student(105,"uma",10);
Set<Student> l = new TreeSet<Student>(new
MyComparator());
l.add(s1);
l.add(s2);
l.add(s3);
l.add(s4);
l.add(s5);
Iterator<Student> i = l.iterator();
while(i.hasNext()) {
System.out.println(i.next());
}
System.out.println("program finished");
}
}
class MyComparator implements Comparator{
@Override
public int compare(Object obj1, Object obj2) {
Student s1 = (Student)obj1;
Student s2 = (Student)obj2;
return -s2.sage.compareTo(s1.sage);
}
}
Lambda Expression on Collection Object sorting
elements based Student name:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Student{
int sid;
String sname;
int sage;
public Student(int sid, String sname, int sage) {
super();
this.sid = sid;
this.sname = sname;
this.sage = sage;
}
@Override
public String toString() {
return sid+"..."+sname+"..."+sage;
}
}
public class Lambda {
public static void main(String[] args) {
Student s1 = new Student(101,"ram",30);
Student s2 = new Student(102,"sam",20);
Student s3 = new Student(103,"varun",40);
Student s4 = new Student(104,"kiran",50);
Student s5 = new Student(105,"uma",10);
List<Student> l = new ArrayList<Student>();
l.add(s1);
l.add(s2);
l.add(s3);
l.add(s4);
l.add(s5);
Collections.sort(l, (p1 ,p2)->{
return p1.sname.compareTo(p2.sname);
});
l.forEach((data)->{
System.out.println(data);
});
}
}
l.forEach((data)->{
System.out.println(data);
});
}
}
System.out.println(st.sid+"..."+st.sname+"..."+st.sag
e);
});
}
}
Method References:
interface Test{
public abstract void check();
}
public class Lambda {
public static void main(String[] args) {
Test t = () -> {
System.out.println("this is test
interface check implementation");
};
t.check();
}
}
class Addition{
public static int addition(int a,int b) {
return a+b;
}
}
public class MethodReference {
BiFunction<Integer,Integer,Integer> bi1 =
(a,b)->{
return (a+b);
};
int j = bi.apply(10, 20);
System.out.println("j: "+j);
class Addition{
public static int addition(int a,int b) {
return a+b;
}
public static float addition(int a,float b) {
return a+b;
}
}
public class MethodReference {
class Addition{
public int addition(int a,int b) {
return a+b;
}
public float addition(int a,float b) {
return a+b;
}
}
public class MethodReference {
Examples on java.util.function.Predicate:
Example1:
import java.util.function.Predicate;
Example2:
import java.util.ArrayList;
import java.util.function.Predicate;
class Student{
int sid;
String sname;
Student(int sid,String sname){
this.sid = sid;
this.sname = sname;
}
public String getSname() {
return sname;
}
}
public class Test1 {
public static void main(String[] args) {
ArrayList<Student> al = new
ArrayList<Student>();
Student s1 = new Student(101,"ram");
Student s2 = new Student(102,"sam");
Student s3 = new Student(103,"kiran");
al.add(s1);
al.add(s2);
al.add(s3);
Program on java.util.function.BiPredicate
import java.util.function.BiPredicate;
public class Test{
public static void main(String[] args) {
BiPredicate<Integer,Integer> bi1 = (x,y)-> x>y ;
boolean b2 = bi1.test(20, 10);
System.out.println("b2: "+b2);
BiPredicate<Integer,Integer> bi2 = (x,y)-> x>y ;
boolean b3 = bi2.test(10, 20);
System.out.println("b3: "+b3);
}
}
Example on java.util.function.Function:
Example1:
import java.util.function.Function;
import java.util.function.Function;
}
}
Example on java.util.function.BiFunction:
Example1:
import java.util.function.BiFunction;
public class Test1 {
public static void main(String[] args) {
BiFunction<Integer,Integer,String> b = (n1,n2)->
"the addition is: "+
(n1+n2);
String s = b.apply(100, 200);
System.out.println("s: "+s);
BiFunction<Integer,Integer,Integer> b1 =
(n1,n2) -> (n1+n2);
int i = b1.apply(11,22);
System.out.println("i: "+i);
}
}
import java.util.function.BiFunction;
public class Test1 {
public static void main(String[] args) {
BiFunction<Integer,Integer,Double> b1 = (n1,n2) ->
{ if(n1>10 && n2>10) {
return (double)(n1+n2);
}
return (double)(n1-n2);
};
double d = b1.apply(50, 60);
System.out.println("d: "+d);
double d1 = b1.apply(10, 5);
System.out.println("d1: "+d1);
}
}
import java.util.function.BiFunction;
public class Test1 {
public static void main(String[] args) {
BiFunction<Integer,Integer,Double> b1 =
(n1,n2) -> (double)(n1+n2);
double d = b1.apply(50, 60);
System.out.println("d: "+d);
double d1 = b1.apply(10, 5);
System.out.println("d1: "+d1);
}
}
Program on java.util.function.Consumer:
import java.util.function.Consumer;
public class Test1 {
public static void main(String[] args)
{ Consumer<Integer> c = (value)->
System.out.println(value);
c.accept(10);
Consumer<String> c1 = (value) ->{
System.out.println(value);
};
c1.accept("ram");
Example on java.util.function.BiConsumer:
import java.util.function.BiConsumer;
public class Test{
public static void main(String[] args) {
BiConsumer<Integer,Integer> bic = (a,b) ->
System.out.println(a+b);
bic.accept(100, 200);
BiConsumer<Integer,String> bic1 = (a,b) ->
System.out.println(a+b);
bic1.accept(100, "good");
BiConsumer<String,String> bic2 = (a,b) ->
System.out.println(a+b);
bic2.accept("ram", "chandra");
}
}
Example on java.util.function.Supplier:
import java.util.Random;
import java.util.function.Supplier;
System.out.println("b: "+b);
return a[b];
};
int i1 = sup1.get();
System.out.println("i1: "+i1);
int i2 = sup1.get();
System.out.println("i2: "+i2);
int i3 = sup1.get();
System.out.println("i3: "+i3);
int i4 = sup1.get();
System.out.println("i4: "+i4);
int i5 = sup1.get();
System.out.println("i5: "+i5);
}
}
Functional Interface:
An interface which contains only one abstract method
is called Functional interface.
Interface I{
Public abstract void m1();
}
It may contain more than one default methods.
Interface J{
Public abstract void m1();
Default void m2(){
}
Default void m3(){
}
}
It may contain more than one static method also.
Interface J{
Public abstract void m1();
static void m2(){
}
static void m3(){
}
}
We can declare more than one of java.lang.Object class
methods.
@FunctionalInterface
interface J{
public abstract void m1();
static void m2(){
}
static void m3(){
}
default void m4() {
}
default void m5() {
}
@Override
public String toString();
@Override
public int hashCode();
}
@FunctionalInterface
interface J{
public abstract void m1();
}
@FunctionalInterface
interface K implements J{
public abstract void m2();
}
interface K extends J{
public abstract void m2();
}
public class Test implements K {
public void m1() {
System.out.println("m1 method");
}
public void m2() {
System.out.println("m2 method");
}
public static void main(String[] args) {
K obj = new Test();
obj.m2();
obj.m1();
}
}
interface J{
public default void m1() {
System.out.println("defalut method m1() from
J interface");
}
}
@FunctionalInterface
interface K extends J{
public abstract void m2();
}
interface J{
public default void m1() {
System.out.println("defalut method m1() from
J interface");
}
public abstract void m3();
}
@FunctionalInterface
interface K extends J{
public abstract void m2();
}
interface I{
public abstract void m1();
}
class A implements I{
public void m1() {
System.out.println("m1-A");
}
}
class B implements I{
public void m1() {
System.out.println("m1-B");
}
}
public class Test{
public static void main(String[] args) {
I obj = new A();
obj.m1();
obj = new B();
obj.m1();
}
}
}
class B implements I{
public void m1() {
System.out.println("m1-B");
}
@Override
public void m2() {
System.out.println("this is override method
of interface-B");
}
}
public class Test{
public static void main(String[] args) {
I obj = new A();
obj.m1();
obj.m2();
obj = new B();
obj.m1();
obj.m2();
}
}
class A implements I{
public void m1() {
System.out.println("m1-A");
}
//bellow code is invalid.
@Override
static public void m2() {
System.out.println("this is override method
of interface-A");
}
}
In the above program we will get error.
}*/
public abstract void m1();
public void m2() {}
}
abstract class AC1 extends AC{
public void m2();//invalid
}
In the above program AC1 related method will give
compile time error.
}
}
}
}
public class Test{
public static void main(String[] args) {
Streams:
A new package like java.util.Stream introduced in java
8.
It is the collection of classes, interfaces and enum for
doing functional programming.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
class Students{
public int sid;
public String sname;
public int sage;
Students(int sid,String sname,int sage){
this.sid = sid;
this.sname = sname;
this.sage = sage;
}
}
public class StreamDemo {
public static void main(String[] args) {
ArrayList<Students> al1 = new
ArrayList<Students>();
Students s1 = new Students(101,"ram1",25);
Students s2 = new Students(102,"ram2",15);
Students s3 = new Students(103,"ram3",35);
Students s4 = new Students(104,"ram4",5);
Students s5 = new Students(105,"ram5",23);
Students s6 = new Students(106,"ram6",39);
Students s7 = new Students(107,"ram7",18);
Students s8 = new Students(108,"ram8",17);
al1.add(s1);
al1.add(s2);
al1.add(s3);
al1.add(s4);
al1.add(s5);
al1.add(s6);
al1.add(s7);
al1.add(s8);
//with stream api
List<Integer> al3 = al1.stream().filter(p ->
p.sage > 19)
.map(p ->
p.sage).collect(Collectors.toList());
System.out.println(al3);
List<String> li = al1.stream().filter(p-
>p.sage>25).map(p->p.sname).
collect(Collectors.toList());
System.out.println(li);
}
}
Methods of Predicate:
import java.util.ArrayList;
import java.util.function.Predicate;
}
}
Example on and() and or() method of predicate:
import java.util.ArrayList;
import java.util.function.Predicate;
public class StreamDemo {
public static void main(String[] args) {
ArrayList<Integer> al1 = new
ArrayList<Integer>();
al1.add(6);
al1.add(18);
al1.add(12);
al1.add(15);
al1.add(4);
al1.add(8);
al1.add(24);
al1.add(10);
System.out.println("al1: "+al1);
Predicate<Integer> p1 = (p3->p3%2==0);
Predicate<Integer> p2 = (p3->p3%3==0);
System.out.print(" : ");
for(Integer i : al1) {
/*if(p1.and(p2).test(i)) {
System.out.print(i+", ");
}*/
if(p1.or(p2).test(i))
System.out.print(i+", ");
}
System.out.println();
System.out.println("al1: "+al1);
}
}
import java.util.function.Predicate;
// Creating predicate
Predicate<Integer> lowerThanTwenty = (i) -> i <
20;
boolean result =
greaterThanTen.and(lowerThanTwenty).test(25);
System.out.println(result);
import java.util.ArrayList;
import java.util.function.Consumer;
public class StreamDemo {
public static void main(String[] args) {
ArrayList<Integer> al = new
ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
al.add(50);
al.add(60);
al.add(70);
System.out.println("al: "+al);
System.out.println("===================");
al.forEach(System.out::println);
System.out.println("===================");
Consumer<Integer> c = (p) ->{System.out.println(p);};
al.forEach(c);
}
}
import java.util.ArrayList;
import java.util.function.Consumer;
public class StreamDemo {
public static void main(String[] args) {
ArrayList<String> al = new
ArrayList<String>();
al.add("ram");
al.add("sam");
al.add("kiran");
al.add("varun");
al.add("mahi");
al.add("vani");
System.out.println("al: "+al);
System.out.println("===================");
al.forEach(System.out::println);
System.out.println("===================");
Consumer<String> c=(p)-
>{System.out.println(p.toUpperCase());};
al.forEach(c);
}
}
}
}
import java.util.ArrayList;
import java.util.stream.Stream;
Java.util.StringJoiner:
}
}
import java.util.StringJoiner;
import java.util.StringJoiner;
import java.util.ArrayList;
import java.util.StringJoiner;
String s2 = sj.toString();
System.out.println("s2: "+s2);
}
}
import java.util.Optional;
Optional<String> o =
Optional.ofNullable(s[3]);
if(o.isPresent()) {
System.out.println(s[3].toUpperCase());
}
else {
System.out.println("there is no value in
that index");
}
}
}
In the above program we have s[3] value like mahi it
will converting into MAHI.
import java.util.Optional;
public class StreamDemo {
public static void main(String[] args) {
String[] s = new String[15];
Optional<String> o =
Optional.ofNullable(s[3]);
if(o.isPresent()) {
System.out.println(s[3].toUpperCase());
}
else {
System.out.println("there is no value in
that index");
}
}
}
In the above scenario there is no value in that index
position but still we are not getting exception
simply it will showing like following message on
console.
There is no value in that index.
import java.util.Optional;
import java.util.Optional;
System.out.println(value.ofNullable(str[5]));
System.out.println(empty.orElse("value is
not present"));
System.out.println(value.orElse("value is
not present"));
}
}
import java.util.Optional;
import java.util.stream.Stream;
Java Nashorn
It is java script engine. We can call and execute the
java script code directly from our command prompt by
using following command like “jjs”.
import javax.script.*;
import java.io.*;
public class Demo{
public static void main(String[] args) throws
Exception{
ScriptEngine ee = new
ScriptEngineManager().getEngineByName("Nashorn");
ee.eval(new FileReader( "C:\\Users\\Ramchandar\\
Desktop\\message.js"));
}
}
Javac Demo.java
Java Demo
Note: we should write in the above program either
“Nashorn” or “nashorn”, otherwise we will get
java.lang.NullPointerException.
ParallelArraySoring:
import java.util.Arrays;
public class ParallelArraySorting {
public static void main(String[] args) {
int[] arr = {5,8,1,0,6,9};
for (int i : arr) {
System.out.print(i+" ");
}
Arrays.parallelSort(arr);
System.out.println("\nArray elements after
sorting");
for (int i : arr) {
System.out.print(i+" ");
}
}
}
}
}
Program on LocalDateTime:
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
Program on LocalTime:
import java.time.LocalTime;