5/9/23, 10:56 AM [Link]
txt
=================
Java 1.8v Features
=================
Java 1.0
Java 1.1
Java 1.2 (Collection Framework)
..
Java 1.5 (Big Release)
..
Java 1.8 (Big Release) ------- Functional Programming
..
Java 19
=================
Java 1.8v Features
=================
-> Java 1.8v introduced lot of new features in java
-> Java 1.8v new features changed java programming style
=========================
Main Objectivies of Java 1.8v
=========================
-> Simplify Java Programming
-> Enable Functional Programming
-> Write more readable and consice code
=================
Java 1.8 Features
=================
1) Interface changes
1.1 ) Default Methods
1.2 ) Static Methods
2) Functional Interfaces (@FunctionalInterface)
2.1 ) Predicate & BiPredicate
2.2 ) Consumer & BiConsumer
2.3 ) Supplier
2.4 ) Function & BiFunction
3) Lambda Expressions
4) Method References & Constructor References
5) ****** Stream API ********
6) Optional class (to avoid null pointer exceptions)
7) Spliterator
[Link] 1/31
5/9/23, 10:56 AM [Link]
8) StringJoiner
9) forEach ( ) method
10) Date & Time API
11) Nashron Engine
12) I/O Stream Changes ([Link](Path p))
13) Base64 Encoding & Decoding
================
Interface changes
================
-> Interface means collection of abstract methods
Note: The method which doesn't contain body is called as abstract method
-> A class can implement interface using "implements"
-> 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 {
public abstract void startVechicle ( );
}
class Car implements Vehicle {
public void startVehicle ( ) {
// logic to start car
}
}
class Bus implements Vehicle {
public void startVehicle ( ) {
// logic to start bus
}
}
class Bike implements Vehicle {
public void startVehicle ( ) {
// logic to start bike
}
}
=> 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
1) Interface can have concreate methods from 1.8v
2) Interface concrete method should be default or static
3) interface default methods we can override in impl classes
4) interface static methods we can't overide in impl classes
5) We can write multiple default & static methods in interface
[Link] 2/31
5/9/23, 10:56 AM [Link]
6) Default & Static method introduced to provide backward compatability
Ex: forEach ( ) method added in [Link] interface as default method in 1.8v
===========
package [Link];
interface Vehicle {
public void start();
public default void m1() {
public default void m2() {
public static void clean() {
[Link]("cleaning completed...");
}
}
public class Car implements Vehicle {
public void start() {
[Link]("car started...");
}
public static void main(String[] args) {
Car c = new Car();
[Link]();
[Link]();
}
}
============================================
=====================
Lambda Expressions
====================
-> Introdced in java 1.8v
-> 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.
-> Lambda Expressions introduced in Java to enable Functional Programming.
==============
What is Lambda
==============
-> Lambda is an anonymous function
- No Name
[Link] 3/31
5/9/23, 10:56 AM [Link]
- No Modifier
- No Return Type
Ex:-1
public void m1 ( ) {
s.o.p("hi");
}
( ) -> { s.o.p ("hi") }
Note: When we have single line in body then curly braces are optional
( ) -> s.o.p ("hi");
Ex:-2
public void add (int a, int b){
s.o.p(a+b);
}
( int a, int b) -> { s.o.p (a+b) } ;
(or)
(int a, int b) -> s.o.p (a+b);
(or)
Lambda Expression : (a, b) -> s.o.p(a+b);
Ex:-3
public int getLength (String name) {
return [Link] ( );
}
(String name) -> { return [Link] ( ) };
(String name) -> return [Link] ( ) ;
(name) -> return [Link] ( );
Lambda Expression : name -> [Link] ( ) ;
Ex:-4
public Double getEmpSalary (Employee emp) {
return [Link] ( );
Lambda Expression : emp -> [Link] ( );
==================
Functional Interfaces
==================
-> The interface which contains only one abstract method is called as Functional Interface
-> Functional Interfaces are used to invoke Lambda expressions
-> Below are some predefined functional interfaces
[Link] 4/31
5/9/23, 10:56 AM [Link]
Runnable ------------> run ( ) method
Callable ----------> call ( ) method
Comparable -------> compareTo ( )
-> 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
1) Predicate & BiPredicate
2) Consumer & BiConsumer
3) Supplier
4) Function & BiFunction
-> The above interfaces are provided in [Link] package
========
Predicate
========
-> It is predefined Functional interface
-> It is used check condition and returns true or false value
-> Predicate interface having only one abstract method that is test (T t)
interface Predicate{
boolean test(T t);
}
// Predicate Example
package [Link].java8;
import [Link];
public class PredicateDemo {
public static void main(String[] args) {
Predicate<Integer> p = i -> i > 10;
[Link]([Link](5));
[Link]([Link](15));
}
=======================================================================================
Task: Declare names in an array and print names which are starting with 'A' using lambda
expression.
String[ ] names = {"Anushka", "Anupama", "Deepika", "Kajol", "Sunny" };
=========================================================================================
[Link] 5/31
5/9/23, 10:56 AM [Link]
package [Link].java8;
import [Link];
public class PredicateDemo2 {
public static void main(String[] args) {
String[ ] names = { "Anushka", "Anupama", "Deepika", "Kajol", "Sunny" };
Predicate<String> p = name -> [Link](0) == 'A';
for (String name : names) {
if ( [Link](name) ) {
[Link](name);
}
}
}
}
============================================================================
Task-2 : Take list of persons and print persons whose age is >= 18 using Lambda Expression
============================================================================
package [Link].java8;
import [Link];
import [Link];
import [Link];
class Person {
String name;
int age;
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}
public class PredicatePersonsDemo {
public static void main(String[] args) {
Person p1 = new Person("John", 26);
Person p2 = new Person("Smith", 16);
Person p3 = new Person("Raja", 36);
Person p4 = new Person("Rani", 6);
List<Person> persons = [Link](p1, p2, p3, p4);
Predicate<Person> predicate = p -> [Link] >= 18;
for (Person person : persons) {
if ([Link](person)) {
[Link]([Link]);
}
}
}
}
================
Predicate Joining
===============
-> To combine multiple predicates we will use Predicate Joining
[Link] 6/31
5/9/23, 10:56 AM [Link]
and ( ) method
or ( ) method
Task-1 : Print emp names who are working in Hyd location in DB team.
package [Link].java8;
import [Link];
import [Link];
import [Link];
class Employee {
String name;
String location;
String dept;
Employee(String name, String location, String dept) {
[Link] = name;
[Link] = location;
[Link] = dept;
}
}
public class PredicateJoinDemo {
public static void main(String[] args) {
Employee e1 = new Employee("Anil", "Chennai", "DevOps");
Employee e2 = new Employee("Rani", "Pune", "Networking");
Employee e3 = new Employee("Ashok", "Hyd", "DB");
Employee e4 = new Employee("Ganesh", "Hyd", "DB");
List<Employee> emps = [Link](e1, e2, e3, e4);
Predicate<Employee> p1 = (e) -> [Link]("Hyd");
Predicate<Employee> p2 = (e) -> [Link]("DB");
Predicate<Employee> p3 = (e) -> [Link]("A");
// Predicate Joining
Predicate<Employee> p = [Link](p2).and(p3);
for (Employee e : emps) {
if ([Link](e)) {
[Link]([Link]);
}
}
}
}
==========================
Supplier Functional Interface
==========================
-> Supplier is a predefined functional interface introduced in java 1.8v
-> It contains only one abstract method that is get ( ) method
-> Supplier interface will not take any input, it will only returns the value.
Ex:
----
OTP Generation
package [Link].java8;
[Link] 7/31
5/9/23, 10:56 AM [Link]
import [Link];
public class SupplierDemo {
public static void main(String[] args) {
Supplier<String> s = () -> {
String otp = "";
for (int i = 1; i <= 6; i++) {
otp = otp + (int) ([Link]() * 10);
}
return otp;
};
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
==========================
Consumer Functional Interface
==========================
-> Consumer is predefined functional interface
-> It contains one abstract method i.e accept (T t)
-> Consumer will accept input but it won't return anything
Note: in java 8 forEach ( ) method got introduced. forEach(Consumer consumer) method will take
Consumer as parameter.
package [Link].java8;
import [Link];
import [Link];
import [Link];
public class ConsumerDemo {
public static void main(String[] args) {
Consumer<String> c = (name) -> [Link](name + ", Good Evening");
[Link]("Ashok");
[Link]("John");
[Link]("Rani");
List<Integer> numbers = [Link](10, 20, 30, 40);
// for loop
// for each loop
// iterator
// list iterator
[Link](i -> [Link](i));
}
}
=========================================================
Retrieve student record based on student id and return that record
=========================================================
[Link] 8/31
5/9/23, 10:56 AM [Link]
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
=========================
-> Function is predefined functional interface
-> Funcation interface having one abstract method i.e apply(T r)
interface Function<R,T>{
R apply (T t);
}
-> It takes input and it returns output
package [Link].java8;
import [Link];
public class FunctionDemo {
public static void main(String[] args) {
Function<String, Integer> f = (name) -> [Link]();
[Link]([Link]("ashokit"));
[Link]([Link]("hyd"));
[Link]([Link]("sachin"));
}
}
=========================================================
Task : Take 2 inputs and perform sum of two inputs and return ouput
=========================================================
BiFunction<Integer,Integer,Integer> bif = (a,b) -> a+b;
Integer sum = [Link](10,20);
================
Method References
=================
-> Method reference means Reference to one method from another method
package [Link].java8;
@FunctionalInterface
interface MyInterface {
public void m1();
}
public class MethodRef {
public static void m2() {
[Link] 9/31
5/9/23, 10:56 AM [Link]
[Link]("This is m2( ) method");
}
public static void main(String[] args) {
MyInterface mi = MethodRef::m2;
mi.m1();
}
}
package [Link].java8;
public class InstanceMethodRef {
public void m1() {
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
public static void main(String[] args) {
InstanceMethodRef im = new InstanceMethodRef();
Runnable r = im::m1;
Thread t = new Thread(r);
[Link]();
}
}
public class Test {
public static void main(String[] args) {
// Doctor d = new Doctor();
Supplier<Doctor> s = Doctor::new;
Doctor doctor = [Link]();
[Link]([Link]());
class Doctor {
public Doctor() {
[Link]("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++) {
[Link](i);
}
}
[Link] 10/31
5/9/23, 10:56 AM [Link]
public static void main(String[] args) {
ThreadDemo1 td = new ThreadDemo1();
Thread t = new Thread(td);
[Link]();
}
}
package [Link].java8;
// Approach-2
public class ThreadDemo2 {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
};
Thread t = new Thread(r);
[Link]();
}
}
// Approach - 3 using Lambda Expression
package [Link].java8;
public class ThreadDemo3 {
public static void main(String[] args) {
Runnable r = () -> {
for (int i = 1; i <= 5; i++) {
[Link](i);
}
};
Thread t = new Thread(r);
[Link]();
}
}
==================================================================
Task: WAJP to store numbers in ArrayList and sort numbers in desending order
==================================================================
// Approach-1 ( without Lambda)
package [Link].java8;
import [Link];
import [Link];
import [Link];
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
[Link](5);
[Link](3);
[Link] 11/31
5/9/23, 10:56 AM [Link]
[Link](4);
[Link](1);
[Link](2);
[Link]("Before Sort :: " + al);
[Link](al, new NumberComparator());
[Link]("After Sort :: " + al);
}
class NumberComparator implements Comparator<Integer> {
@Override
public int compare(Integer i, Integer j) {
if (i > j) {
return -1;
} else if (i < j) {
return 1;
}
return 0;
}
}
// Approach-2 ( with Lambda)
package [Link].java8;
import [Link];
import [Link];
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
[Link](5);
[Link](3);
[Link](4);
[Link](1);
[Link](2);
[Link]("Before Sort :: " + al);
[Link](al, (i, j) -> (i > j) ? -1 : 1);
[Link]("After Sort :: " + al);
}
}
==========================
forEach (Consumer c) method
===========================
-> forEach (Consumer c) method introduced in java 1.8v
-> forEach ( ) method added in Iterable interface
-> forEach ( ) method is a default method (it is having body)
-> This is method is used to access each element of the collection (traverse collection from start
to end)
package [Link].java8;
import [Link];
[Link] 12/31
5/9/23, 10:56 AM [Link]
public class NumbersSort1 {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
[Link](5);
[Link](3);
[Link](4);
[Link](1);
[Link](2);
[Link](i -> [Link](i));
}
}
==============
StringJoiner
==============
-> [Link] class introduced in java 1.8v
-> It is used to join more than one String with specified delimiter
-> We can concat prefix and suffix while joininging strings using StringJoiner
StringJoiner sj = new StringJoiner (CharSequence delim);
StringJoiner sj = new StringJoiner (CharSequence delim, CharSequence prefix,
CharSequence suffix);
package [Link].java8;
import [Link];
public class StringJoinerDemo {
public static void main(String[] args) {
StringJoiner sj1 = new StringJoiner("-");
[Link]("ashok");
[Link]("it");
[Link]("java");
[Link](sj1); // ashok-it-java
StringJoiner sj2 = new StringJoiner("-", "(", ")");
[Link]("ashok");
[Link]("it");
[Link]("java");
[Link](sj2); // (ashok-it-java)
=============
Optional Class
=============
-> [Link] class introduced in java 1.8v
-> Optional class is used to avoid NullPointerExceptions in the program
[Link] 13/31
5/9/23, 10:56 AM [Link]
Q) What is NullPointerException (NPE) ?
Ans) When we perform some operation on null value then we will get NullPointerException
String s = null;
[Link] ( ) ; // NPE
-> To avoid NullPointerExceptions we have to implement null check before performing operation on
the Object like below.
String s = null;
if( s! = null ) {
[Link]([Link] ( ));
}
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 [Link].java8;
import [Link];
public class User {
// Without Optional object
public String getUsernameById(Integer id) {
if (id == 100) {
return "Raju";
} else if (id == 101) {
return "Rani";
} else if (id == 102) {
return "John";
} else {
return null;
}
}
// with Optional Object
public Optional<String> getUsername(Integer id) {
String name = null;
if (id == 100) {
name = "Raju";
} else if (id == 101) {
name = "Rani";
} else if (id == 102) {
name = "John";
}
return [Link](name);
}
}
package [Link].java8;
import [Link];
import [Link];
public class MsgService {
[Link] 14/31
5/9/23, 10:56 AM [Link]
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter User ID");
int userId = [Link]();
User u = new User();
/*String userName = [Link](userId);
String msg = [Link]() + ", Hello";
[Link](msg);*/
Optional<String> username = [Link](userId);
if([Link]()) {
String name = [Link]();
[Link]([Link]()+", Hello");
}else {
[Link]("No Data Found");
}
}
}
=======================
Date & Time API Changes
=======================
-> In java we have below 2 classes to represent Date
1) [Link]
2) [Link]
Note: When we are performing database operations then we will use [Link] class.
-> For normal Date related operations we will use [Link] class
Date d = new Date ( );
[Link](d);
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.
========================
[Link]
=======================
-> SimpleDateFormat is a predefined class in [Link] pacakage
-> This class provided methods to perform Date conversions
Date to String conversion ===> String format (Date d)
String to Date conversion ===> Date parse(String str)
// Date Conversions Example
package [Link].java8;
import [Link];
import [Link];
[Link] 15/31
5/9/23, 10:56 AM [Link]
public class DateDemo {
public static void main(String[] args) throws Exception {
Date date = new Date();
[Link](date);
// Converting Date to String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
String format1 = [Link](date);
[Link](format1);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy");
String format2 = [Link](date);
[Link](format2);
// Convert String to Date
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = [Link]("2022-12-20");
[Link](parsedDate);
}
}
=========================================================================================
=> To overcome the problems of [Link] class java 1.8 introduced Date API changes
=> In java 1.8 version, new classes got introduced to deal with Date & Time functionalities
1) [Link] (it will deal with only date)
2) [Link] (it will deal with only time)
3) [Link] (it will deal with both date & time)
// Java 1.8 Date API Example
package [Link].java8;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class NewDateDemo {
public static void main(String[] args) {
LocalDate of = [Link](2021, 1, 20);
[Link](of);
LocalDate date = [Link]();
[Link](date);
date = [Link](3);
[Link](date);
date = [Link](1);
[Link](date);
date = [Link](2);
[Link](date);
boolean leapYear = [Link]("2020-12-22").isLeapYear();
[Link] 16/31
5/9/23, 10:56 AM [Link]
[Link]("Leap Year :: " + leapYear);
boolean before = [Link]("2021-12-22").isBefore([Link]("2022-12-
22"));
[Link]("Before Date : " + before);
LocalTime time = [Link]();
[Link](time);
time = [Link](2);
[Link](time);
LocalDateTime datetime = [Link]();
[Link](datetime);
Period period = [Link]([Link]("1991-05-20"), [Link]());
[Link](period);
Duration duration = [Link]([Link]("18:00"), [Link]());
[Link](duration);
}
}
=================
1) What are new changes in java 8 version
2) Interface Changes
2.1 ) Default Methods
2.2 ) Static Methods
3) Why Default & Static method introduced in java 8
4) Lambda Expressions Introduction
5) How to write Lambda Expression
6) How to invoke lambda expression
7) Functional Interfaces
7.1) Predicate & BiPredicate
7.2) Supplier
7.3) Consumer & BiConsumer
7.4) Function & BiFunction
8) Collections Sorting using Lambda
9) Thread Creation Using Lambda
10) Method References & Constructor References
11) [Link] class
12) [Link] class
13) forEach ( Consumer c ) method
14) Date & Time API Changes
14.1) LocalDate
14.2) LocalTime
14.3) LocalDateTime
14.4) Period
14.5) Duration
===========
[Link] 17/31
5/9/23, 10:56 AM [Link]
Stream API
===========
-> Stream API introduced in java 1.8v
-> Stream API is used to process the data
Note: Collections are used to store the data
-> 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.
-> Source of data for the Stream can be array or collection
===============================
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
===============
-> In Java we can create Stream in 2 ways
1) [Link] (e1, e2, e3, e4.....)
2) stream ( ) method
// Java Program to Create Stream
package [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
// Approach-1
Stream<Integer> stream1 = [Link](1, 2, 3, 4, 5);
ArrayList<String> names = new ArrayList<>();
[Link]("John");
[Link]("Robert");
[Link]("Orlen");
// Approach-2
Stream<String> stream2 = [Link]();
}
}
===================
Stream Operations
===================
-> Stream API provided several methods to perform Operations on the data
[Link] 18/31
5/9/23, 10:56 AM [Link]
-> We can divide Stream api methods into 2 types
1) Intermediate Operational Methods
2) Terminal Operational Methods
-> Intermediate Operational methods will perform operations on the stream and returns a new Stream
Ex: filter ( ) , map ( ) etc....
-> Terminal Operational methods will take input and will provide result as output.
Ex: count ( )
===================
Filtering with Streams
===================
-> Filtering means getting required data from original data
Ex: get only even numbers from given numbers
Ex: get emps whose salary is >= 1,00,000
Ex: Get Mobiles whose price is <= 15,000
-> To apply filter on the data, Stream api provided filter ( ) method
Ex : Stream filter (Predicate p)
===================
Example - 1 : Filter
==================
package [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
List<Integer> list = [Link](66, 32, 45, 12, 20);
/*for (Integer i : list) {
if (i > 20) {
[Link](i);
}
}*/
/*Stream<Integer> stream = [Link]();
Stream<Integer> filteredStrem = [Link](i -> i > 20);
[Link](i -> [Link](i));*/
[Link]().filter(i -> i > 20).forEach(i -> [Link](i));
}
}
[Link] 19/31
5/9/23, 10:56 AM [Link]
==========================
Example - 2 : Filter
========================
package [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
List<String> names = [Link]("John", "Anushka", "Anupama", "Smith",
"Ashok");
[Link]().filter(i -> [Link]("A")).forEach(i -> [Link](i));
}
}
==================
Example - 3 : Filter
==================
package [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
User u1 = new User("Anushka", 25);
User u2 = new User("Smith", 30);
User u3 = new User("Raju", 15);
User u4 = new User("Rani", 10);
User u5 = new User("Charles", 35);
User u6 = new User("Ashok", 30);
Stream<User> stream = [Link](u1, u2, u3, u4, u5, u6);
// [Link](u -> [Link] >= 18).forEach(u -> [Link](u));
/*[Link](u -> [Link] >= 18 && [Link]("A"))
.forEach(u -> [Link](u));*/
[Link](u -> [Link] >= 18)
.filter(u -> [Link]("A"))
.forEach(u -> [Link](u));
}
}
class User {
String name;
int age;
User(String name, int age) {
[Link] = name;
[Link] = age;
}
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
[Link] 20/31
5/9/23, 10:56 AM [Link]
===================
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
Ex : Stream map (Function function) ;
=======================
Example-1 : map ( ) method
=======================
public class FirstDemo {
public static void main(String[] args) {
List<String> names = [Link]("india","usa","uk", "japan");
/*for(String name : names) {
[Link]([Link]());
}*/
[Link]().map(name -> [Link]()).forEach(n ->
[Link](n));
[Link]().mapToInt(name -> [Link]()).forEach(i ->
[Link](i));
}
}
=========================
Example-2 : map ( ) method
========================
public class FirstDemo {
public static void main(String[] args) {
List<String> names = [Link]("Ashok", "Anil", "Raju", "Rani", "John",
"Akash", "Charles");
// print name with its length which are starting with 'A' using Stream API
//Ashok - 5
//Anil - 4
//Akash - 5
[Link]()
.filter(name -> [Link]("A"))
.map(name -> name + "-" +[Link]())
.forEach(name -> [Link](name));
}
}
=======================
Example-3 : map ( ) method
========================
class Employee ( ) {
[Link] 21/31
5/9/23, 10:56 AM [Link]
String name;
int age;
double salary;
Task : Print Emp Name with Emp age whose salary is >= 50,000 using Stream API.
public class FirstDemo {
public static void main(String[] args) {
Employee e1 = new Employee("John", 35, 55000.00);
Employee e2 = new Employee("David", 25, 45000.00);
Employee e3 = new Employee("Buttler", 35, 35000.00);
Employee e4 = new Employee("Steve", 45, 65000.00);
Stream<Employee> stream = [Link](e1, e2, e3, e4);
/*[Link](e -> [Link] >= 50000.00)
.map(e -> [Link]+" - " +[Link])
.forEach(e -> [Link](e));*/
[Link](e -> [Link] >= 50000.00)
.forEach(e -> [Link]([Link] + "-" + [Link]));
}
}
class Employee {
String name;
int age;
double salary;
public Employee(String name, int age, double salary) {
[Link] = name;
[Link] = age;
[Link] = salary;
}
}
===================================
Q) What is flatMap(Function f) method ?
===================================
-> It is used to flaten list of streams into single stream
public class FirstDemo {
public static void main(String[] args) {
List<String> javacourses = [Link]("core java", "adv java", "springboot");
List<String> uicourses = [Link]("html", "css", "bs", "js");
List<List<String>> courses = [Link](javacourses, uicourses);
//[Link]().forEach(c -> [Link](c));
Stream<String> fms = [Link]().flatMap(s -> [Link]());
[Link](c -> [Link](c));
}
}
[Link] 22/31
5/9/23, 10:56 AM [Link]
==========================
Slicing Operations with Stream
==========================
1) distinct ( ) => To get unique elements from the 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 [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
List<String> javacourses = [Link]("corejava", "advjava", "springboot",
"restapi", "microservices");
[Link]().limit(3).forEach(c -> [Link](c));
[Link]().skip(3).forEach(c -> [Link](c));
List<String> names = [Link]("raja", "rani", "raja", "rani", "guru");
[Link]().distinct().forEach(name -> [Link](name));
}
}
============================
Matching Operations with Stream
============================
1) boolean anyMatch (Predicate p )
2) boolean allMatch (Predicate p )
3) boolean noneMatch (Predicate p )
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 [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
List<Person> persons = [Link](p1, p2, p3, p4);
[Link] 23/31
5/9/23, 10:56 AM [Link]
boolean status1 = [Link]().anyMatch(p -> [Link]("INDIA"));
[Link]("Any Indian Available ? :: " + status1);
boolean status2 = [Link]().anyMatch(p -> [Link]("CANADA"));
[Link]("Any Canadian Available ? :: " + status2);
boolean status3 = [Link]().allMatch(p -> [Link]("INDIA"));
[Link]("All Persons from India ? :: " + status3);
boolean status4 = [Link]().noneMatch(p -> [Link]("MEXICO"));
[Link]("No Persons from Mexico ? :: " + status4);
}
}
class Person {
String name;
String country;
public Person(String name, String country) {
[Link] = name;
[Link] = country;
}
===================
Collectors with Stream
==================
-> Collectors are used to collect data from Stream
===================
Example-1 : Collectors
===================
package [Link];
import [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
Person p5 = new Person("Kumar", "INDIA");
List<Person> persons = [Link](p1, p2, p3, p4, p5);
List<Person> indians = [Link]()
.filter(p ->
[Link]("INDIA"))
.collect([Link]());
[Link](i -> [Link](i));
}
}
class Person {
[Link] 24/31
5/9/23, 10:56 AM [Link]
String name;
String country;
public Person(String name, String country) {
[Link] = name;
[Link] = country;
}
@Override
public String toString() {
return "Person [name=" + name + ", country=" + country + "]";
}
===================
Example-2: Collectors
===================
package [Link];
import [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
Person p1 = new Person("John", "USA");
Person p2 = new Person("Steve", "JAPAN");
Person p3 = new Person("Ashok", "INDIA");
Person p4 = new Person("Ching", "CHINA");
Person p5 = new Person("Kumar", "INDIA");
List<Person> persons = [Link](p1, p2, p3, p4, p5);
// collect names of persons who are belongs to india and store into names
collection
List<String> names = [Link]()
.filter(p ->
[Link]("INDIA"))
.map(p -> [Link])
.collect([Link]());
[Link](names);
}
}
class Person {
String name;
String country;
public Person(String name, String country) {
[Link] = name;
[Link] = country;
}
@Override
public String toString() {
return "Person [name=" + name + ", country=" + country + "]";
}
[Link] 25/31
5/9/23, 10:56 AM [Link]
==============================================
Set - 1 : Intermediate Operations (will return Stream)
==============================================
Filters ----> filter ( )
Mappings ----> map ( ) & flatMap ( )
Slicing ----> distinct ( ) & limit () & skip ( )
==============================================
Set - 2 : Terminal Operations (will return result)
==============================================
Finding ---> findFirst ( ) & findAny ( )
Matching ---> anyMatch ( ) & allMatch ( ) & noneMatch ( )
Collecting ---> collect ( )
============
Requirement
===========
=> Write a java program to get MAX, MIN and AVG salary from given employees data using Stream API.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "Robert", 26500.00);
Employee e2 = new Employee(2, "Abraham", 46500.00);
Employee e3 = new Employee(3, "Ching", 36500.00);
Employee e4 = new Employee(4, "David", 16500.00);
Employee e5 = new Employee(5, "Cathy", 25500.00);
List<Employee> list = [Link](e1, e2, e3, e4, e5);
Optional<Employee> max = [Link]()
.collect([Link]([Link](e -> [Link])));
[Link]("Max Salary :: " + [Link]().salary);
Optional<Employee> min = [Link]()
.collect([Link]([Link](e -> [Link])));
[Link]("Min Salary :: " + [Link]().salary);
Double avgSalary = [Link]().collect([Link](e ->
[Link]));
[Link] 26/31
5/9/23, 10:56 AM [Link]
[Link](avgSalary);
}
}
class Employee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}
}
====================
Group By using Stream
====================
-> Group By is used categorize the data / Grouping the data
-> When we use groupingBy ( ) function with stream they it will group the data as Key-Value(s)
pair and it will return Map object
-> In below example employees will be grouped based on Country name.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FirstDemo {
public static void main(String[] args) {
Employee e1 = new Employee(1, "Robert", 26500.00, "USA");
Employee e2 = new Employee(2, "Abraham", 46500.00, "INDIA");
Employee e3 = new Employee(3, "Ching", 36500.00, "CHINA");
Employee e4 = new Employee(4, "David", 16500.00, "INDIA");
Employee e5 = new Employee(5, "Cathy", 25500.00, "USA") ;
List<Employee> list = [Link](e1, e2, e3, e4, e5);
Map<String, List<Employee>> data = [Link]()
.collect([Link](e -> [Link]));
[Link](data);
}
}
class Employee {
int id;
String name;
double salary;
String country;
public Employee(int id, String name, double salary, String country) {
[Link] = id;
[Link] = name;
[Link] = salary;
[Link] = country;
}
} public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
================ }
Parallel Streams
[Link] 27/31
5/9/23, 10:56 AM [Link]
===============
-> Generally Streams will execute in sequence order
-> To improve execution process of the stream we can use parallel streams
-> Paralell Streams introduced to improve performance of the program.
package [Link];
import [Link];
public class ParallelDemo {
public static void main(String[] args) {
[Link]("====== Serial Stream ========");
Stream<Integer> ss = [Link](1, 2, 3, 4);
[Link](n -> [Link](n + " :: " + [Link]()));
[Link]("====== Parallel Strem =======");
Stream<Integer> ps = [Link](1, 2, 3, 4);
[Link]().forEach(n -> [Link](n + " :: " +
[Link]()));
}
}
==============
Java Spliterator
==============
-> Like Iterator and ListIterator, Spliterator is one of the Java Iterator
-> Spliterator introduced in java 1.8v
-> Spliterator is an interface in collections api
-> Spliterator supports both serial & paralell programming
-> Spliterator we can use to traverse both Collections & Streams
-> Spliterator can't be used with Map implementation classes
package [Link];
import [Link];
import [Link];
import [Link];
public class ParallelDemo {
public static void main(String[] args) {
List<String> names = [Link]("sachin", "sehwag", "dhoni");
Spliterator<String> spliterator = [Link]().spliterator();
[Link](n -> [Link](n));
}
}
=============
[Link] 28/31
5/9/23, 10:56 AM [Link]
Stream Reduce
=============
package demo;
import [Link];
public class Sum {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5 };
/*int sum = 0;
for(int i : nums) {
sum = sum + i;
}
[Link](sum);*/
int reduce = [Link](nums).reduce(0, (a,b) -> a+b);
[Link](reduce);
}
}
======================
Nashorn Engine in Java 1.8
======================
-> Nashorn is a Java Script Engine which is used to execute Java Script code using JVM
-> Create a javascript file like below (filename : [Link])
--------------------- [Link] --------------------------
var hello = function(){
print("Welcome to JavaScript");
}
hello();
------------------------------------------------------
-> Open command prompt and execute below command
syntax : jjs [Link]
-> We can execute above Java Script file using Java program like below
import [Link].*;
import [Link].*;
public class Demo {
public static void main(String... args) throws Exception {
ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn");
[Link](new FileReader("[Link]"));
}
}
==========================
I/O Streams Changes in Java 8
[Link] 29/31
5/9/23, 10:56 AM [Link]
==========================
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
FileReader ----> It will read the data character by character (slow
performance)
BufferedReader ---> It will read the data line by line
[Link](Path path) ---> It will read all lines at a time and returns
as a Stream
package demo;
import [Link];
import [Link];
import [Link];
public class ReadFileData {
public static void main(String[] args) throws Exception {
/*FileReader fr = new FileReader(new File("[Link]"));
BufferedReader br = new BufferedReader(fr);
String line = [Link]();
while (line != null) {
[Link](line);
line = [Link]();
}
[Link]();*/
String filename = "[Link]";
try (Stream<String> stream = [Link]([Link](filename))){
[Link](line -> [Link](line));
}catch(Exception e) {
[Link]();
}
}
}
=======================
Java 8 Base64 Changes
=======================
-> Base64 is a predefined class available in [Link] package
-> Base64 class providing methods to perform encoding and decoding
Encoder encoder = [Link]();
// converting String to byte[] and passing as input for encode( ) method
byte[] encode = [Link]([Link]());
// Converting byte[] to String
[Link] 30/31
5/9/23, 10:56 AM [Link]
String encodedPwd = new String(encode);
[Link](encodedPwd);
Decoder decoder = [Link]();
byte[ ] decode = [Link](encodedPwd);
String decodedPwd = new String(decode);
[Link](decodedPwd);
[Link] 31/31