Java 8 Example
Java 8 Example
-> When a class is implementing interface its 5) We can write multiple default & static methods in
mandatory that class should implement all abstract interface
methods of that interface othewise class can't be 6) Default & Static method introduced to provide
compile. backward compatability
} }
public void start() { Note: When we have single line in body then curly
[Link]("car starte..."); braces are optional
-> In OOP language Classes & Objects are main public int getLength (String name) {
entities. We need to write methods inside the class return [Link] ( );
only.
}
-> Functional Programming means everything will be
represented in the form functions. Functions can exist (String name) -> { return [Link] ( ) };
outside of the class. Functions can be stored into a (String name) -> return [Link] ( ) ;
reference variable. A function can be passed as a
parameter to other methods. (name) -> return [Link] ( );
// Predicate Example
Comparable ------->
import [Link];
compareTo ( )
4) Function & BiFunction Task: Declare names in an array and print names
which are starting with 'A' using lambda expression.
String[ ] names = {"Anushka", package [Link].java8;
"Anupama", "Deepika", "Kajol", "Sunny" };
import [Link];
============================================
import [Link];
============================================
= import [Link];
int age;
public class PredicateDemo2 {
[Link] = age;
String[ ] names = { "Anushka", }
"Anupama", "Deepika", "Kajol", "Sunny" };
}
if ( [Link](name) ) {
Person p1 = new Person("John", 26);
[Link](name); 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 ->
Task-2 : Take list of persons and print persons whose [Link] >= 18;
age is >= 18 using Lambda Expression
}
public class PredicateJoinDemo {
================
public static void main(String[] args) {
Predicate Joining
Employee e1 = new Employee("Anil",
=============== "Chennai", "DevOps");
Employee e4 = new
and ( ) method
Employee("Ganesh", "Hyd", "DB");
or ( ) method
List<Employee> emps =
[Link](e1, e2, e3, e4);
Predicate<Employee> p =
class Employee { [Link](p2).and(p3);
String dept;
[Link]([Link]);
}
Employee(String name, String location, String
dept) { }
[Link] = name; }
} return otp;
};
==========================
========================== [Link]([Link]());
[Link]([Link]());
[Link]([Link]());
-> It contains only one abstract method that is get ( )
}
method
}
-> Supplier interface will not take any input, it will only
returns the value. ==========================
[Link]("Ashok");
=========================
[Link]("John");
Function Functional Interface
[Link]("Rani");
=========================
List<Integer> numbers =
[Link](10, 20, 30, 40); -> Function is predefined functional interface
// for loop
// for each loop -> Funcation interface having one abstract method i.e
apply(T r)
// iterator
// list iterator
interface Function<R,T>{
R apply (T t);
[Link](i ->
[Link](i)); }
============================================
=============
package [Link].java8;
Retrieve student record based on student id and
return that record
import [Link];
============================================
=============
Predicate ------> takes inputs ----> returns true or false public static void main(String[] args) {
===> test ( )
[Link]([Link]("ashokit"));
[Link]([Link]("hyd")); public static void m2() {
}
}
}
public static void main(String[] args) {
MyInterface mi = MethodRef::m2;
============================================
============= mi.m1();
package [Link].java8;
[Link](i);
================
}
Method References
}
=================
InstanceMethodRef im = new
InstanceMethodRef();
package [Link].java8;
Runnable r = im::m1;
interface MyInterface {
[Link]();
public void m1();
}
}
}
[Link]();
} }
}
public static void main(String[] args) {
}
@Override
============================================
public void run() {
===============================
for (int i = 1; i <= 5;
Task : WAJP to print numbers from 1 to 5 using Thread
i++) {
with the help of Runnable interface
============================================
[Link](i);
================================
}
};
//Approach-1
} import [Link];
} import [Link];
package [Link].java8;
ArrayList<Integer> al = new
ArrayList<>();
public static void main(String[] args) {
[Link](5);
[Link](3);
Runnable r = () -> {
[Link](4);
for (int i = 1; i <= 5; i++) {
[Link](1);
[Link](i);
[Link](2);
}
};
[Link]("Before Sort :: " +
al);
Thread t = new Thread(r);
[Link]();
[Link](al, new
} NumberComparator());
}
[Link]("After Sort :: " +
al);
}
============================================
======================
============================================
class NumberComparator implements
======================
Comparator<Integer> {
@Override
return -1;
package [Link].java8;
} else if (i < j) {
return 1;
} ==========================
} ===========================
package [Link].java8;
-> forEach ( ) method is a default method (it is having
body)
import [Link];
import [Link];
-> This is method is used to access each element of
the collection (traverse collection from start to end)
[Link](5);
public class NumbersSort1 {
[Link](3);
[Link](4);
public static void main(String[] args) {
[Link](1);
[Link](2);
ArrayList<Integer> al = new
ArrayList<>();
[Link](4);
[Link](al, (i, j) -> (i > j) ? -1 :
[Link](1);
1);
[Link](2);
} }
} }
==============
[Link]("it");
-> [Link] class introduced in java 1.8v
[Link]("java");
[Link](sj2); // (ashok-it-
-> It is used to join more than one String with
java)
specified delimiter
}
-> We can concat prefix and suffix while joininging
strings using StringJoiner
=============
import [Link];
[Link]("it");
[Link] ( ) ; // NPE
[Link]("java");
[Link](sj1); // ashok-it-
java
-> To avoid NullPointerExceptions we have to } else {
implement null check before performing operation on
return null;
the Object like below.
}
}
String s = null;
name = "Raju";
name = "Rani";
Note: In project there is no gaurantee that every
programmer will implement null checks. If any body } else if (id == 102) {
forgot to implement null check then program will run
into NullPointerException. name = "John";
-> To avoid this problem we need to use Optional class return [Link](name);
like below. }
package [Link].java8;
package [Link].java8;
import [Link];
import [Link];
public class User { import [Link];
/*String userName =
[Link](userId); -> For normal Date related operations we will use
[Link] class
String msg = [Link]()
+ ", Hello";
[Link](d);
Optional<String> username =
[Link](userId);
Note: When we create Object for Date class, it will
represent both date and time.
if([Link]()) {
String name = [Link](); -> If we want to get only date or only time then we
need to format it using SimpleDateFormat class.
[Link]([Link]()+",
Hello");
}else {
========================
[Link]("No Data
[Link]
Found");
=======================
}
}
-> SimpleDateFormat is a predefined class in [Link]
}
pacakage
=======================
2) [Link]
// Date Conversions Example
package [Link].java8;
=> To overcome the problems of [Link] class
java 1.8 introduced Date API changes
import [Link];
import [Link];
=> In java 1.8 version, new classes got introduced to
deal with Date & Time functionalities
public class DateDemo {
1) [Link]
public static void main(String[] args) throws (it will deal with only date)
Exception {
2) [Link]
Date date = new Date(); (it will deal with only time)
[Link](date);
3)
[Link] (it will deal with both date &
// Converting Date to String time)
SimpleDateFormat sdf1 = new
SimpleDateFormat("dd/MM/yyyy");
[Link](format1);
// Java 1.8 Date API Example
import [Link];
}
LocalDate of = [Link](2021, 1,
20);
============================================
[Link](of);
============================================
=
}
date = [Link](1);
[Link](date);
date = [Link](2);
=================
[Link](date);
[Link](datetime);
7.1) Predicate & BiPredicate
7.2) Supplier
Period period =
[Link]([Link]("1991-05-20"), 7.3) Consumer & BiConsumer
[Link]()); 7.4) Function & BiFunction
[Link](period);
14) Date & Time API Changes 2) Stream will not change original data structure of
the source (It will just process the data given by the
source.)
14.1) LocalDate
14.2) LocalTime
Ex: filter ( ) ,
// Approach-1
map ( ) etc....
Stream<Integer> stream1 =
[Link](1, 2, 3, 4, 5);
[Link]("John");
Ex: count ( )
[Link]("Robert");
[Link]("Orlen");
===================
// Approach-2
Filtering with Streams
Stream<String> stream2 =
[Link](); ===================
===================
Ex: get emps whose salary is >=
1,00,000
1) Intermediate Operational -> To apply filter on the data, Stream api provided
Methods filter ( ) method
Example - 1 : Filter
==================
==========================
Example - 2 : Filter
import [Link];
import [Link];
List<String> names =
/*for (Integer i : list) { [Link]("John", "Anushka", "Anupama", "Smith",
"Ashok");
if (i > 20) {
[Link](i);
[Link]().filter(i ->
}
[Link]("A")).forEach(i -> [Link](i));
}*/
}
/*Stream<Integer> stream =
}
[Link]();
==================
Stream<Integer> filteredStrem =
[Link](i -> i > 20); Example - 3 : Filter
==================
[Link](i ->
[Link](i));*/
package [Link];
Mapping Operations
.forEach(u ->
-> Mapping operations are used to transform the
[Link](u));*/
stream elements and return transformed elements as
new Stream
.filter(u ->
[Link]("A"))
Ex : Stream map (Function function) ;
.forEach(u ->
[Link](u));
}
=======================
}
Example-1 : map ( ) method
=======================
class User {
int age;
public static void main(String[] args) {
.filter(name ->
[Link]([Link]()); [Link]("A"))
.forEach(name ->
[Link]().map(name ->
[Link](name));
[Link]()).forEach(n ->
[Link](n)); }
[Link]().mapToInt(name ->
[Link]()).forEach(i -> [Link](i));
=======================
}
Example-3 : map ( ) method
}
========================
=========================
class Employee ( ) {
Example-2 : map ( ) method
========================
String name;
int age;
public class FirstDemo {
double salary;
//Anil
-4 Employee e1 = new Employee("John",
35, 55000.00);
Employee e2 = new
Employee("David", 25, 45000.00);
===================================
Employee e3 = new
Q) What is flatMap(Function f) method ?
Employee("Buttler", 35, 35000.00);
===================================
Employee e4 = new
Employee("Steve", 45, 65000.00);
} //[Link]().forEach(c ->
[Link](c));
class Employee {
Stream<String> fms =
[Link]().flatMap(s -> [Link]());
String name;
int age;
[Link](c ->
double salary; [Link](c));
[Link] = age;
==========================
[Link] = salary;
Slicing Operations with Stream
}
==========================
}
[Link]().distinct().forEach(name ->
1) distinct ( ) => To get unique elements from the
[Link](name));
Stream
}
2) limit ( long maxSize ) => Get elements from the
stream based on given size }
============================
Note: All the above 3 methods are comes under
Intermediate Operational Methods. They will perform
operation and returns new Stream. 1) boolean anyMatch (Predicate p )
List<String> javacourses =
[Link]("corejava", "advjava", "springboot", package [Link];
"restapi", "microservices");
import [Link];
[Link]().limit(3).forEach(c
import [Link];
-> [Link](c));
}
List<Person> persons =
[Link](p1, p2, p3, p4);
}
boolean status1 =
[Link]().anyMatch(p -> ===================
[Link]("INDIA")); Collectors with Stream
[Link]("Any Indian ==================
Available ? :: " + status1);
===================
boolean status3 =
[Link]().allMatch(p ->
[Link]("INDIA"));
package [Link];
[Link]("All Persons from
India ? :: " + status3);
import [Link];
import [Link];
boolean status4 =
[Link]().noneMatch(p -> import [Link];
[Link]("MEXICO"));
}
Person p1 = new Person("John",
"USA");
class Person {
Person p2 = new Person("Steve",
"JAPAN");
String name;
Person p3 = new Person("Ashok", }
"INDIA");
Example-2: Collectors
List<Person> persons = ===================
[Link](p1, p2, p3, p4, p5);
package [Link];
List<Person> indians =
[Link]()
import [Link];
.filter(p -> import [Link];
[Link]("INDIA"))
import [Link];
.collect([Link]());
public class FirstDemo {
[Link](i ->
[Link](i)); public static void main(String[] args) {
[Link] = name;
List<Person> persons =
[Link] = country; [Link](p1, p2, p3, p4, p5);
}
.map(p -> [Link]) Slicing ----> distinct ( ) & limit () & skip ( )
.collect([Link]());
[Link](names);
============================================
} ==
} Set - 2 : Terminal Operations (will return result)
============================================
==
class Person {
String country;
Matching ---> anyMatch ( ) & allMatch ( ) &
noneMatch ( )
public Person(String name, String country) {
[Link] = name;
Collecting ---> collect ( )
[Link] = country;
@Override
}
============
Requirement
}
===========
============================================
==
package [Link];
Filters ----> filter ( )
import [Link]; .collect([Link]([Link]
ng(e -> [Link])));
import [Link];
import [Link];
[Link]("Min Salary :: " +
import [Link];
[Link]().salary);
import [Link];
Double avgSalary =
public class FirstDemo { [Link]().collect([Link](e ->
[Link]));
[Link](avgSalary);
public static void main(String[] args) {
}
}
Employee e1 = new Employee(1,
"Robert", 26500.00);
[Link] = id;
}
Optional<Employee> max =
}
[Link]()
====================
.collect([Link]([Link]
ng(e -> [Link]))); Group By using Stream
====================
Optional<Employee> min =
[Link]() -> 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 class Employee {
on Country name.
int id;
String name;
package [Link];
double salary;
String country;
import [Link];
import [Link];
public Employee(int id, String name, double
import [Link]; salary, String country) {
[Link] = name;
[Link] = country;
Employee e4 = new Employee(4, -> Generally Streams will execute in sequence order
"David", 16500.00, "INDIA");
[Link]("====== Serial
Stream ========");
import [Link];
[Link]("====== Parallel
Strem =======");
[Link]().forEach(n ->
[Link](n + " :: " + public static void main(String[] args) {
[Link]()));
} List<String> names =
} [Link]("sachin", "sehwag", "dhoni");
Spliterator<String> spliterator =
[Link]().spliterator();
==============
Java Spliterator
[Link](n ->
============== [Link](n));
}
-> Like Iterator and ListIterator, Spliterator is one of }
the Java Iterator
Stream Reduce
-> Spliterator supports both serial & paralell
programming =============
import [Link];
public class Sum {
hello();
------------------------------------------------------
int[] nums = { 1, 2, 3, 4, 5 };
for(int i : nums) {
syntax : jjs [Link]
sum = sum + i;
[Link](sum);*/
-> We can execute above Java Script file using Java
program like below
int reduce =
[Link](nums).reduce(0, (a,b) -> a+b);
[Link](reduce);
import [Link].*;
}
import [Link].*;
}
======================
ScriptEngine se = new
ScriptEngineManager().getEngineByName("Nashorn");
}
-> Create a javascript file like below (filename : [Link])
}
}
Task : Write a java program to read a file data and
print it on the console
while (line != null) {
[Link](line);
line = [Link]();
-> To read file data we can use FileReader &
}
BufferedReader classes
[Link]();*/
[Link](line ->
[Link](line));
[Link](Path path) ---> It
will read all lines at a time and returns as a Stream
}catch(Exception e) {
[Link]();
}
package demo;
}
}
import [Link];
import [Link];
import [Link];
byte[] encode =
[Link]([Link]()); ============================================
==================
.collect([Link]([Link]
1. How many male and female employees are there in
ngDouble(Employee::getSalary)));
the organization ?
if([Link]()) {
Employee employee =
Map<String, Long> map1 =
[Link]();
[Link]().collect([Link](Employe
e::getGender, [Link]()));
[Link](employee);
[Link](map1);
}
.map(Employee::getDepartment) [Link]()
.forEach(name ->
[Link](name));
3. What is the average age of male and female
employees ?
[Link](map);
.collect([Link](Employee::getD
epartment, [Link]()));
[Link](map);
.collect([Link](Employee::getD
Map<String, Long> map =
epartment,
[Link]()
[Link](Employee::getSalary)));
[Link](map);
.filter(e ->
[Link]().equals("Sales"))
.collect([Link]([Link]
ng(Employee::getYearOfJoining)));
if([Link]()) {
[Link]([Link]());