SlideShare a Scribd company logo
1 of 22
Java 8 Training
-Marut Singh
Email: Singh.marut@gmail.com
http://www.marutsingh.com/
https://github.com/singhmarut/java8training
http://marutsingh.com/
About Me
 12 years in Software Industry
 Build software in Project Management, Banking, Education, Ecommerce
 C++,C #.Net, Java, Scala, Akka, Spring, Node.JS, Vert.x, RDBMS, MongoDB
 Singh.marut@gmail.com
http://marutsingh.com/
1. Collections Streams, and Filters
 Iterating through a collection using lambda syntax
 Describing the Stream interface
 Filtering a collection using lambda expressions
 Calling an existing method using a method reference
 Chaining multiple methods together
 Defining pipelines in terms of lambdas and collections
2. Lambda Built-in Functional Interfaces
 Listing the built-in interfaces included in java.util.function
 Core interfaces - Predicate, Consumer, Function, Supplier
 Using primitive versions of base interfaces
 Using binary versions of base interfaces
3. Lambda Operations
 Extracting data from an object using map
 Describing the types of stream operations
 Describing the Optional class
 Describing lazy processing
 Sorting a stream
 Saving results to a collection using the collect method
 Grouping and partition data using the Collectors class
4 .Java Date/Time API
 Creating and manage date-based events
 Creating and manage time-based events
 Combining date and time into a single object
 Working with dates and times across time zones
 Managing changes resulting from daylight savings
 Defining and create timestamps, periods and durations
 Applying formatting to local and zoned dates and times
5. File I/O (NIO.2)
 Using the Path interface to operate on file and directory paths
 Using the Files class to check, delete, copy, or move a file or directory
 Using Stream API with NIO2
6. Parallel Streams
 Reviewing the key characteristics of streams
 Describing how to make a stream pipeline execute in parallel
 List the key assumptions needed to use a parallel pipeline
 Defining reduction
 Describing why reduction requires an associative function
 Calculating a value using reduce
 Describing the process for decomposing and then merging work
 Listing the key performance considerations for parallel streams
http://marutsingh.com/
Functional Programming
 In computer science, functional programming is a programming paradigm—a
style of building the structure and elements of computer programs—that
treats computation as the evaluation of mathematical functions and avoids
changing-state and mutable data. It is a declarative programming paradigm,
which means programming is done with expressions[1] or
declarations[2] instead of statements. In functional code, the output value of
a function depends only on the arguments that are input to the function, so
calling a function f twice with the same value for an argument x will produce
the same result f(x)each time. Eliminating side effects, i.e. changes in state
that do not depend on the function inputs, can make it much easier to
understand and predict the behavior of a program, which is one of the key
motivations for the development of functional programming.- Wikipedia
http://marutsingh.com/
Basis of functional programming
 Function as first class entity
 Functions with no side-effect
 A method, which modifies neither the state of its enclosing class nor the state of
any other objects and returns its entire results using return, is called pure or side-
effect free.
f(x,y) => x + y
 Immutability
 An immutable object is an object that can’t change its state after it’s instantiated
so it can’t be affected by the actions of a function
 This means that once immutable objects are instantiated, they can never go
into an unexpected state. You can share them without having to copy them,
and they’re thread-safe because they can’t be modified
http://marutsingh.com/
Collections Streams, and Filters
http://marutsingh.com/
Benefits of Functional Programming
 Concise code
 Easy to reason about
 No side effects
 Easy to parallelize
http://marutsingh.com/
Functional Languages
 Haskell
 Closure
 Scala
 OCaml
 F#
 Linq
 Python/Javascript
http://marutsingh.com/
Lambda Expression
 Lambda expressions define anonymous methods that are treated as instances of
functional interfaces.
 A lambda expression is composed of parameters, an arrow, and a body.
 An arrow— The arrow -> separates the list of parameters from the body of the
lambda.
 The body of the lambda— e.g. Compare two objects using their attributes. The
expression is considered the lambda’s return value.
 As a result lambdas are
 it doesn’t have an explicit name like a method would normally have
 isn’t associated with a particular class like a method is
 Passed around
 Concise You don’t need to write a lot of boilerplate like you do for anonymous classes.
http://marutsingh.com/
Examples of lambdas
Use case Examples of lambdas
A boolean expression (List<String> list) -> list.isEmpty()
Creating objects () -> new Car()
Consuming from an object (Car a) -> {
System.out.println(a.getBrand()); }
Select/extract from an object (String s) -> s.length()
Combine two values (int a, int b) -> a * b
Compare two objects (Car c1, Car c2) ->
c1.getWeight().compareTo(c2.getWeight
())http://marutsingh.com/
Quiz
 Based on the syntax rules just shown, which of the following are not valid
lambda expressions?
1. ()->{}
2. () -> "Raoul"
3. () -> {return "Mario";}
4. (Integer i) -> return "Alan" + i;
5. (String s) -> {"Iron Man";}
http://marutsingh.com/
Where to use Lambda?
 You can use a lambda expression in the context of a functional interface.
 Stream interface exposes many useful methods which take functional
interface as an argument. That’s where Lambda can be used
http://marutsingh.com/
Iteration Code Demo
 public static void printCars(List<Car> carList){
//carList.forEach((Car car) -> car.print());
carList.forEach(car -> {
car.print();
});
}
http://marutsingh.com/
Streams
A sequence of elements supporting sequential and parallel aggregate operations.
 Similarities with collections but not collections
 Do not provide a means to directly access or manipulate their elements, and are
instead concerned with declaratively describing their source and the
computational operations which will be performed in aggregate on that source
 No storage. A stream is not a data structure that stores elements; instead, it
conveys elements from a source such as a data structure, an array, a generator
function, or an I/O channel, through a pipeline of computational operations.
 Functional in nature. An operation on a stream produces a result, but does not
modify its source.
 Laziness-seeking.
 Possibly unbounded. While collections have a finite size, streams need not.
 Consumable. The elements of a stream are only visited once during the life of a
stream. Like an Iterator, a new stream must be generated to revisit the same
elements of the source.
http://marutsingh.com/
Streams
 Iterating through a collection using lambda syntax
List<Car> carList = new ArrayList<>();
carList.forEach(car -> System.out.println(car));
 Stream Interface
 Filtering
public static void filterByBrand(List<Car> carList,String brand){
carList.stream()
.filter(car -> car.getBrand().equalsIgnoreCase(brand))
.forEach(car -> printCar(car));
}
http://marutsingh.com/
Streams
 They support two types of operations: intermediate operations such as filter
or map and terminal operations such as count, findFirst, forEach, and reduce.
 Intermediate operations can be chained to convert a stream into another
stream. These operations don’t consume from a stream; their purpose is to
set up a pipeline of streams. By contrast, terminal operations do consume
from a stream—to produce a final result (for example, returning the largest
element in a stream). They can often shorten computations by optimizing the
pipeline of a stream
http://marutsingh.com/
Filtering
 public static void filterCars(List<Car> carList,String brand) {
carList.stream()
.filter( car -> car.getBrand().equals(brand))
.forEach(car -> car.print());
}
 Code Demo
http://marutsingh.com/
Method Reference
 You use lambda expressions to create anonymous methods. Sometimes,
however, a lambda expression does nothing but call an existing method. In
those cases, it's often clearer to refer to the existing method by name.
Method references enable you to do this; they are compact, easy-to-read
lambda expressions for methods that already have a name.
 1. A method reference to a static method (for example, the method parseInt
of Integer, written Integer::parseInt)
 2. A method reference to an instance method of an arbitrary type (for
example, the method length of a String, written String::length)
 3. A method reference to an instance method of an existing object
http://marutsingh.com/
Functional Interface
 A functional interface is an interface that specifies exactly one abstract
method.
 All functional interfaces have been defined under java.util.function package
 @FunctionalInterface
 public interface Predicate<T>{ boolean test (T t) };
 public interface Comparator<T>{ int compaare(T o1,T o2) };
 Public interface Callable<V> { V call(); }
http://marutsingh.com/
Subtle Mistakes When Using the Streams API
 Accidentally re-using Stream
IntStream stream = IntStream.of(1, 2);
stream.forEach(System.out::println);
// That was fun! Let's do it again!
stream.forEach(System.out::println);
java.lang.IllegalStateException: stream has already been operated upon or closed
http://marutsingh.com/
Subtle Mistakes When Using the Streams API
 Accidentally creating infinite streams
// Will run indefinitely
IntStream.iterate(0, i -> i + 1)
.forEach(System.out::println);
http://marutsingh.com/
Core Interfaces in java.util.function
 Predicate
 Consumer
 Function
 Supplier
http://marutsingh.com/

More Related Content

What's hot

Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoagillygize
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
Lexical and Parser tool for CBOOP program
Lexical and Parser tool for CBOOP programLexical and Parser tool for CBOOP program
Lexical and Parser tool for CBOOP programIOSR Journals
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Rohit Agrawal
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...Flink Forward
 
Dax Declarative Api For Xml
Dax   Declarative Api For XmlDax   Declarative Api For Xml
Dax Declarative Api For XmlLars Trieloff
 
Codecamp iasi-26 nov 2011-what's new in jpa 2.0
Codecamp iasi-26 nov 2011-what's new in jpa 2.0Codecamp iasi-26 nov 2011-what's new in jpa 2.0
Codecamp iasi-26 nov 2011-what's new in jpa 2.0Codecamp Romania
 
plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....Abhiram Vijay
 
Lecture02 abap on line
Lecture02 abap on lineLecture02 abap on line
Lecture02 abap on lineMilind Patil
 
AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...
AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...
AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...GeeksLab Odessa
 

What's hot (20)

Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoa
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Spark
SparkSpark
Spark
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
Lexical and Parser tool for CBOOP program
Lexical and Parser tool for CBOOP programLexical and Parser tool for CBOOP program
Lexical and Parser tool for CBOOP program
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3
 
Unit 3 lecture-2
Unit 3 lecture-2Unit 3 lecture-2
Unit 3 lecture-2
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
 
Dax Declarative Api For Xml
Dax   Declarative Api For XmlDax   Declarative Api For Xml
Dax Declarative Api For Xml
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Linq
LinqLinq
Linq
 
Codecamp iasi-26 nov 2011-what's new in jpa 2.0
Codecamp iasi-26 nov 2011-what's new in jpa 2.0Codecamp iasi-26 nov 2011-what's new in jpa 2.0
Codecamp iasi-26 nov 2011-what's new in jpa 2.0
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....
 
Lecture02 abap on line
Lecture02 abap on lineLecture02 abap on line
Lecture02 abap on line
 
AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...
AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...
AI&BigData Lab.Руденко Петр. Automation and optimisation of machine learning ...
 
Unit 3
Unit 3Unit 3
Unit 3
 
Unit 4-apache pig
Unit 4-apache pigUnit 4-apache pig
Unit 4-apache pig
 

Viewers also liked

Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2Marut Singh
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph DatabaseTobias Lindaaker
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On WorkshopArpit Poladia
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel ProgrammingRamazan AYYILDIZ
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Alexander Pashynskiy
 
Why Transcriptome? Why RNA-Seq? ENCODE answers….
Why Transcriptome? Why RNA-Seq?  ENCODE answers….Why Transcriptome? Why RNA-Seq?  ENCODE answers….
Why Transcriptome? Why RNA-Seq? ENCODE answers….Mohammad Hossein Banabazi
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsRahul Malhotra
 

Viewers also liked (20)

Java8 training - class 2
Java8 training - class 2Java8 training - class 2
Java8 training - class 2
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Building Applications with a Graph Database
Building Applications with a Graph DatabaseBuilding Applications with a Graph Database
Building Applications with a Graph Database
 
What is concurrency
What is concurrencyWhat is concurrency
What is concurrency
 
Java8
Java8Java8
Java8
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
Apache camel
Apache camelApache camel
Apache camel
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
 
Why Transcriptome? Why RNA-Seq? ENCODE answers….
Why Transcriptome? Why RNA-Seq?  ENCODE answers….Why Transcriptome? Why RNA-Seq?  ENCODE answers….
Why Transcriptome? Why RNA-Seq? ENCODE answers….
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
dna Imprinting
 dna Imprinting dna Imprinting
dna Imprinting
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp concepts
 
Java Concurrent
Java ConcurrentJava Concurrent
Java Concurrent
 

Similar to Java8 training - Class 1

Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APIPrabu U
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An OverviewIndrajit Das
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails SiddheshSiddhesh Bhobe
 
6 10-presentation
6 10-presentation6 10-presentation
6 10-presentationRemi Arnaud
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured StreamingKnoldus Inc.
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaJignesh Aakoliya
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...jaxLondonConference
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.docabdulhaq467432
 

Similar to Java8 training - Class 1 (20)

Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
Java 8
Java 8Java 8
Java 8
 
Lambda.pdf
Lambda.pdfLambda.pdf
Lambda.pdf
 
6 10-presentation
6 10-presentation6 10-presentation
6 10-presentation
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Unit 1
Unit  1Unit  1
Unit 1
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
 
Apouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-futureApouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-future
 

Recently uploaded

Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Recently uploaded (20)

Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Java8 training - Class 1

  • 1. Java 8 Training -Marut Singh Email: Singh.marut@gmail.com http://www.marutsingh.com/ https://github.com/singhmarut/java8training http://marutsingh.com/
  • 2. About Me  12 years in Software Industry  Build software in Project Management, Banking, Education, Ecommerce  C++,C #.Net, Java, Scala, Akka, Spring, Node.JS, Vert.x, RDBMS, MongoDB  Singh.marut@gmail.com http://marutsingh.com/
  • 3. 1. Collections Streams, and Filters  Iterating through a collection using lambda syntax  Describing the Stream interface  Filtering a collection using lambda expressions  Calling an existing method using a method reference  Chaining multiple methods together  Defining pipelines in terms of lambdas and collections 2. Lambda Built-in Functional Interfaces  Listing the built-in interfaces included in java.util.function  Core interfaces - Predicate, Consumer, Function, Supplier  Using primitive versions of base interfaces  Using binary versions of base interfaces 3. Lambda Operations  Extracting data from an object using map  Describing the types of stream operations  Describing the Optional class  Describing lazy processing  Sorting a stream  Saving results to a collection using the collect method  Grouping and partition data using the Collectors class 4 .Java Date/Time API  Creating and manage date-based events  Creating and manage time-based events  Combining date and time into a single object  Working with dates and times across time zones  Managing changes resulting from daylight savings  Defining and create timestamps, periods and durations  Applying formatting to local and zoned dates and times 5. File I/O (NIO.2)  Using the Path interface to operate on file and directory paths  Using the Files class to check, delete, copy, or move a file or directory  Using Stream API with NIO2 6. Parallel Streams  Reviewing the key characteristics of streams  Describing how to make a stream pipeline execute in parallel  List the key assumptions needed to use a parallel pipeline  Defining reduction  Describing why reduction requires an associative function  Calculating a value using reduce  Describing the process for decomposing and then merging work  Listing the key performance considerations for parallel streams http://marutsingh.com/
  • 4. Functional Programming  In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions[1] or declarations[2] instead of statements. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x)each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.- Wikipedia http://marutsingh.com/
  • 5. Basis of functional programming  Function as first class entity  Functions with no side-effect  A method, which modifies neither the state of its enclosing class nor the state of any other objects and returns its entire results using return, is called pure or side- effect free. f(x,y) => x + y  Immutability  An immutable object is an object that can’t change its state after it’s instantiated so it can’t be affected by the actions of a function  This means that once immutable objects are instantiated, they can never go into an unexpected state. You can share them without having to copy them, and they’re thread-safe because they can’t be modified http://marutsingh.com/
  • 6. Collections Streams, and Filters http://marutsingh.com/
  • 7. Benefits of Functional Programming  Concise code  Easy to reason about  No side effects  Easy to parallelize http://marutsingh.com/
  • 8. Functional Languages  Haskell  Closure  Scala  OCaml  F#  Linq  Python/Javascript http://marutsingh.com/
  • 9. Lambda Expression  Lambda expressions define anonymous methods that are treated as instances of functional interfaces.  A lambda expression is composed of parameters, an arrow, and a body.  An arrow— The arrow -> separates the list of parameters from the body of the lambda.  The body of the lambda— e.g. Compare two objects using their attributes. The expression is considered the lambda’s return value.  As a result lambdas are  it doesn’t have an explicit name like a method would normally have  isn’t associated with a particular class like a method is  Passed around  Concise You don’t need to write a lot of boilerplate like you do for anonymous classes. http://marutsingh.com/
  • 10. Examples of lambdas Use case Examples of lambdas A boolean expression (List<String> list) -> list.isEmpty() Creating objects () -> new Car() Consuming from an object (Car a) -> { System.out.println(a.getBrand()); } Select/extract from an object (String s) -> s.length() Combine two values (int a, int b) -> a * b Compare two objects (Car c1, Car c2) -> c1.getWeight().compareTo(c2.getWeight ())http://marutsingh.com/
  • 11. Quiz  Based on the syntax rules just shown, which of the following are not valid lambda expressions? 1. ()->{} 2. () -> "Raoul" 3. () -> {return "Mario";} 4. (Integer i) -> return "Alan" + i; 5. (String s) -> {"Iron Man";} http://marutsingh.com/
  • 12. Where to use Lambda?  You can use a lambda expression in the context of a functional interface.  Stream interface exposes many useful methods which take functional interface as an argument. That’s where Lambda can be used http://marutsingh.com/
  • 13. Iteration Code Demo  public static void printCars(List<Car> carList){ //carList.forEach((Car car) -> car.print()); carList.forEach(car -> { car.print(); }); } http://marutsingh.com/
  • 14. Streams A sequence of elements supporting sequential and parallel aggregate operations.  Similarities with collections but not collections  Do not provide a means to directly access or manipulate their elements, and are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source  No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.  Functional in nature. An operation on a stream produces a result, but does not modify its source.  Laziness-seeking.  Possibly unbounded. While collections have a finite size, streams need not.  Consumable. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. http://marutsingh.com/
  • 15. Streams  Iterating through a collection using lambda syntax List<Car> carList = new ArrayList<>(); carList.forEach(car -> System.out.println(car));  Stream Interface  Filtering public static void filterByBrand(List<Car> carList,String brand){ carList.stream() .filter(car -> car.getBrand().equalsIgnoreCase(brand)) .forEach(car -> printCar(car)); } http://marutsingh.com/
  • 16. Streams  They support two types of operations: intermediate operations such as filter or map and terminal operations such as count, findFirst, forEach, and reduce.  Intermediate operations can be chained to convert a stream into another stream. These operations don’t consume from a stream; their purpose is to set up a pipeline of streams. By contrast, terminal operations do consume from a stream—to produce a final result (for example, returning the largest element in a stream). They can often shorten computations by optimizing the pipeline of a stream http://marutsingh.com/
  • 17. Filtering  public static void filterCars(List<Car> carList,String brand) { carList.stream() .filter( car -> car.getBrand().equals(brand)) .forEach(car -> car.print()); }  Code Demo http://marutsingh.com/
  • 18. Method Reference  You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.  1. A method reference to a static method (for example, the method parseInt of Integer, written Integer::parseInt)  2. A method reference to an instance method of an arbitrary type (for example, the method length of a String, written String::length)  3. A method reference to an instance method of an existing object http://marutsingh.com/
  • 19. Functional Interface  A functional interface is an interface that specifies exactly one abstract method.  All functional interfaces have been defined under java.util.function package  @FunctionalInterface  public interface Predicate<T>{ boolean test (T t) };  public interface Comparator<T>{ int compaare(T o1,T o2) };  Public interface Callable<V> { V call(); } http://marutsingh.com/
  • 20. Subtle Mistakes When Using the Streams API  Accidentally re-using Stream IntStream stream = IntStream.of(1, 2); stream.forEach(System.out::println); // That was fun! Let's do it again! stream.forEach(System.out::println); java.lang.IllegalStateException: stream has already been operated upon or closed http://marutsingh.com/
  • 21. Subtle Mistakes When Using the Streams API  Accidentally creating infinite streams // Will run indefinitely IntStream.iterate(0, i -> i + 1) .forEach(System.out::println); http://marutsingh.com/
  • 22. Core Interfaces in java.util.function  Predicate  Consumer  Function  Supplier http://marutsingh.com/