Java 1.8v Features
Java 1.8v Features
txt
=================
Java 1.8v Features
=================
Java 1.0
Java 1.1
..
..
..
Java 19
=================
Java 1.8v Features
=================
=========================
Main Objectivies of Java 1.8v
=========================
=================
Java 1.8 Features
=================
1) Interface changes
3) Lambda Expressions
7) Spliterator
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 1/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
8) StringJoiner
9) forEach ( ) method
================
Interface changes
================
Note: The method which doesn't contain body is called as abstract method
-> When a class is implementing interface its mandatory that class should implement all abstract
methods of that interface othewise class can't be compile.
=> Here i am taking one interface with one abstract method. All the classes which are implementing
that interface should overide interface method(s).
interface Vehicle {
=> If we add new method in interface then Car, Bike and Bus will fail at compile time.
=> To overcome above problem we will use Default & Static methods
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 2/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
===========
package in.ashokit;
interface Vehicle {
public void start();
=====================
Lambda Expressions
====================
-> Java is called as Object Oriented Programming language. Everything will be represented using
Classes and Objects.
-> From 1.8v onwards Java is also called as Functional Programming Language.
-> In OOP language Classes & Objects are main entities. We need to write methods inside the class
only.
-> Functional Programming means everything will be represented in the form functions. Functions
can exist outside of the class. Functions can be stored into a reference variable. A function can
be passed as a parameter to other methods.
==============
What is Lambda
==============
- No Name
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 3/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
- No Modifier
- No Return Type
Ex:-1
public void m1 ( ) {
s.o.p("hi");
}
Note: When we have single line in body then curly braces are optional
Ex:-2
(or)
(or)
Ex:-3
Ex:-4
return emp.getSalary ( );
==================
Functional Interfaces
==================
-> The interface which contains only one abstract method is called as Functional Interface
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 4/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
-> To represent one interface as Functional Interface we will use @FunctionalInterface annotation.
@FunctionalInterface
public interface MyInterface {
public void m1( );
}
Note: When we write @FunctionalInterface then our compiler will check interface contains only one
abstract method or not.
-> In Java 8 several predefined Functional interfaces got introduced they are
========
Predicate
========
-> Predicate interface having only one abstract method that is test (T t)
interface Predicate{
boolean test(T t);
}
// Predicate Example
package in.ashokit.java8;
import java.util.function.Predicate;
=======================================================================================
Task: Declare names in an array and print names which are starting with 'A' using lambda
expression.
=========================================================================================
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 5/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
package in.ashokit.java8;
import java.util.function.Predicate;
============================================================================
Task-2 : Take list of persons and print persons whose age is >= 18 using Lambda Expression
============================================================================
package in.ashokit.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
class Person {
String name;
int age;
================
Predicate Joining
===============
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 6/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
and ( ) method
or ( ) method
Task-1 : Print emp names who are working in Hyd location in DB team.
package in.ashokit.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
class Employee {
String name;
String location;
String dept;
// Predicate Joining
Predicate<Employee> p = p1.and(p2).and(p3);
==========================
Supplier Functional Interface
==========================
-> Supplier interface will not take any input, it will only returns the value.
Ex:
----
OTP Generation
package in.ashokit.java8;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 7/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
import java.util.function.Supplier;
Supplier<String> s = () -> {
String otp = "";
for (int i = 1; i <= 6; i++) {
otp = otp + (int) (Math.random() * 10);
}
return otp;
};
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
System.out.println(s.get());
}
}
==========================
Consumer Functional Interface
==========================
Note: in java 8 forEach ( ) method got introduced. forEach(Consumer consumer) method will take
Consumer as parameter.
package in.ashokit.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
c.accept("Ashok");
c.accept("John");
c.accept("Rani");
=========================================================
Retrieve student record based on student id and return that record
=========================================================
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 8/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
Predicate ------> takes inputs ----> returns true or false ===> test ( )
Supplier -----> will not take any input---> returns output ===> get ( )
Consumer ----> will take input ----> will not return anything ===> accept ( )
Function -----> will take input ---> will return output ===> apply ( )
=========================
Function Functional Interface
=========================
interface Function<R,T>{
R apply (T t);
}
package in.ashokit.java8;
import java.util.function.Function;
System.out.println(f.apply("ashokit"));
System.out.println(f.apply("hyd"));
System.out.println(f.apply("sachin"));
}
}
=========================================================
Task : Take 2 inputs and perform sum of two inputs and return ouput
=========================================================
================
Method References
=================
-> Method reference means Reference to one method from another method
package in.ashokit.java8;
@FunctionalInterface
interface MyInterface {
public void m1();
}
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 9/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
package in.ashokit.java8;
Runnable r = im::m1;
Thread t = new Thread(r);
t.start();
}
}
Supplier<Doctor> s = Doctor::new;
Doctor doctor = s.get();
System.out.println(doctor.hashCode());
class Doctor {
public Doctor() {
System.out.println("Doctor constructor....");
}
}
===========================================================================
Task : WAJP to print numbers from 1 to 5 using Thread with the help of Runnable interface
============================================================================
//Approach-1
public class ThreadDemo1 implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 10/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
package in.ashokit.java8;
// Approach-2
public class ThreadDemo2 {
Runnable r = () -> {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
};
==================================================================
Task: WAJP to store numbers in ArrayList and sort numbers in desending order
==================================================================
package in.ashokit.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 11/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
al.add(4);
al.add(1);
al.add(2);
package in.ashokit.java8;
import java.util.ArrayList;
import java.util.Collections;
==========================
forEach (Consumer c) method
===========================
-> This is method is used to access each element of the collection (traverse collection from start
to end)
package in.ashokit.java8;
import java.util.ArrayList;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 12/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
==============
StringJoiner
==============
-> It is used to join more than one String with specified delimiter
-> We can concat prefix and suffix while joininging strings using StringJoiner
package in.ashokit.java8;
import java.util.StringJoiner;
=============
Optional Class
=============
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 13/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
Ans) When we perform some operation on null value then we will get NullPointerException
String s = null;
s.length ( ) ; // NPE
-> To avoid NullPointerExceptions we have to implement null check before performing operation on
the Object like below.
String s = null;
if( s! = null ) {
System.out.println(s.length ( ));
}
Note: In project there is no gaurantee that every programmer will implement null checks. If any
body forgot to implement null check then program will run into NullPointerException.
-> To avoid this problem we need to use Optional class like below.
package in.ashokit.java8;
import java.util.Optional;
package in.ashokit.java8;
import java.util.Optional;
import java.util.Scanner;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 14/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
if(username.isPresent()) {
String name = username.get();
System.out.println(name.toUpperCase()+", Hello");
}else {
System.out.println("No Data Found");
}
}
}
=======================
Date & Time API Changes
=======================
1) java.util.Date
2) java.sql.Date
Note: When we are performing database operations then we will use java.sql.Date class.
-> For normal Date related operations we will use java.util.Date class
Note: When we create Object for Date class, it will represent both date and time.
-> If we want to get only date or only time then we need to format it using SimpleDateFormat
class.
========================
java.text.SimpleDateFormat
=======================
package in.ashokit.java8;
import java.text.SimpleDateFormat;
import java.util.Date;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 15/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
}
}
=========================================================================================
=> To overcome the problems of java.util.Date class java 1.8 introduced Date API changes
=> In java 1.8 version, new classes got introduced to deal with Date & Time functionalities
package in.ashokit.java8;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
date = date.plusDays(3);
System.out.println(date);
date = date.plusMonths(1);
System.out.println(date);
date = date.plusYears(2);
System.out.println(date);
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 16/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
=================
2) Interface Changes
7) Functional Interfaces
14.1) LocalDate
14.2) LocalTime
14.3) LocalDateTime
14.4) Period
14.5) Duration
===========
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 17/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
Stream API
===========
-> Stream API is one of the major features added in java 1.8v
-> Stream in java can be defined as sequence of elements that comes from a source.
===============================
Few Important Points About Streams
===============================
1) Stream is not a data structure. Stream means bunch of operations applied on source data. Source
can be collection or array.
2) Stream will not change original data structure of the source (It will just process the data
given by the source.)
===============
Stream Creation
===============
2) stream ( ) method
package in.ashokit.streams;
import java.util.ArrayList;
import java.util.stream.Stream;
// Approach-1
Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5);
// Approach-2
Stream<String> stream2 = names.stream();
}
}
===================
Stream Operations
===================
-> Stream API provided several methods to perform Operations on the data
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 18/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
-> Intermediate Operational methods will perform operations on the stream and returns a new Stream
-> Terminal Operational methods will take input and will provide result as output.
Ex: count ( )
===================
Filtering with Streams
===================
-> To apply filter on the data, Stream api provided filter ( ) method
===================
Example - 1 : Filter
==================
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
}
}
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 19/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
==========================
Example - 2 : Filter
========================
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
}
}
==================
Example - 3 : Filter
==================
package in.ashokit.streams;
import java.util.stream.Stream;
}
}
class User {
String name;
int age;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 20/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
===================
Mapping Operations
===================
-> Mapping operations are belongs to intermediate operations in the Stream api
-> Mapping operations are used to transform the stream elements and return transformed elements as
new Stream
=======================
Example-1 : map ( ) method
=======================
}
}
=========================
Example-2 : map ( ) method
========================
// print name with its length which are starting with 'A' using Stream API
//Ashok - 5
//Anil - 4
//Akash - 5
names.stream()
.filter(name -> name.startsWith("A"))
.map(name -> name + "-" +name.length())
.forEach(name -> System.out.println(name));
}
}
=======================
Example-3 : map ( ) method
========================
class Employee ( ) {
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 21/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
String name;
int age;
double salary;
Task : Print Emp Name with Emp age whose salary is >= 50,000 using Stream API.
}
}
class Employee {
String name;
int age;
double salary;
===================================
Q) What is flatMap(Function f) method ?
===================================
}
}
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 22/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
==========================
Slicing Operations with Stream
==========================
2) limit ( long maxSize ) => Get elements from the stream based on given size
3) skip (long n) => It is used to skip given number of elements from starting position of the
stream
Note: All the above 3 methods are comes under Intermediate Operational Methods. They will perform
operation and returns new Stream.
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
}
}
============================
Matching Operations with Stream
============================
Note: The above 3 methods are belongs to Terminal Operations because they will do operation and
they will return result directley (they won't return stream)
-> The above methods are used to check the given condition and returns true or false value based
on condition.
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 23/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
}
}
class Person {
String name;
String country;
===================
Collectors with Stream
==================
===================
Example-1 : Collectors
===================
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
.collect(Collectors.toList());
}
}
class Person {
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 24/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
String name;
String country;
@Override
public String toString() {
return "Person [name=" + name + ", country=" + country + "]";
}
===================
Example-2: Collectors
===================
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// collect names of persons who are belongs to india and store into names
collection
.collect(Collectors.toList());
System.out.println(names);
}
}
class Person {
String name;
String country;
@Override
public String toString() {
return "Person [name=" + name + ", country=" + country + "]";
}
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 25/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
==============================================
Set - 1 : Intermediate Operations (will return Stream)
==============================================
==============================================
Set - 2 : Terminal Operations (will return result)
==============================================
============
Requirement
===========
=> Write a java program to get MAX, MIN and AVG salary from given employees data using Stream API.
package in.ashokit.streams;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 26/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
System.out.println(avgSalary);
}
}
class Employee {
int id;
String name;
double salary;
====================
Group By using Stream
====================
-> When we use groupingBy ( ) function with stream they it will group the data as Key-Value(s)
pair and it will return Map object
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
System.out.println(data);
}
}
class Employee {
int id;
String name;
double salary;
String country;
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 27/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
===============
-> To improve execution process of the stream we can use parallel streams
package in.ashokit.streams;
import java.util.stream.Stream;
==============
Java Spliterator
==============
-> Like Iterator and ListIterator, Spliterator is one of the Java Iterator
package in.ashokit.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;
=============
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 28/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
Stream Reduce
=============
package demo;
import java.util.Arrays;
int[] nums = { 1, 2, 3, 4, 5 };
/*int sum = 0;
for(int i : nums) {
sum = sum + i;
}
System.out.println(sum);*/
}
}
======================
Nashorn Engine in Java 1.8
======================
-> Nashorn is a Java Script Engine which is used to execute Java Script code using JVM
hello();
------------------------------------------------------
-> We can execute above Java Script file using Java program like below
import java.io.*;
import javax.script.*;
se.eval(new FileReader("one.js"));
}
}
==========================
I/O Streams Changes in Java 8
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 29/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
==========================
Task : Write a java program to read a file data and print it on the console
-> To read file data we can use FileReader & BufferedReader classes
Files.lines(Path path) ---> It will read all lines at a time and returns
as a Stream
package demo;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
}catch(Exception e) {
e.printStackTrace();
}
}
}
=======================
Java 8 Base64 Changes
=======================
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 30/31
5/9/23, 10:56 AM https://ashokitech.com/uploads/notes/1069835451_1672328246.txt
System.out.println(encodedPwd);
https://ashokitech.com/uploads/notes/1069835451_1672328246.txt 31/31