SlideShare une entreprise Scribd logo
1  sur  38
Java 8 Streams
&
Common Operations
By Harmeet Singh(Taara)
(Java EE Developer)
Email: harmeetsingh.0013@gmail.com
Blog: http://harmeetsingh13.blogspot.in
Skype: harmeetsingh0013
Contact: Via Email or Skype
Contents
➢ Introduction
➢ High-Order Functions
➢ Effective Final Variables
➢ Lexical-Scoping
➢ Method References
➢ Internal-Iterators
➢ External-Iterators
➢ Stream’s Common’s Operation
➢ Stream’s Collectors
➢ Optional Class
➢ Leftover: The Things We Didn’t Cover
Acknowledgment
➢ Special Thanks To My Parents.
➢ Thanks To All, Who Support Me or Not.
➢ Dedicated To My Teacher “Mr. Kapil Sakhuja”
➢ Thanks To Insonix.
Introduction
Today, We cover Java 8 Stream API’s for remove some
‘Boilerplate Code’ from our daily programming. In Java,
Some time we need to write some common practices with
our collections for fetching the elements and do some
operations.
This make’s our code dirty. Java 8 Streams provide some
powerful operations for our collections libraries. It is
basically perform operation like SQL queries on java
collections.
(Download Examples :
https://github.com/harmeetsingh0013/Java8-Streams-
Examples.git)
Higher-Order Functions
➢ In OO-Programming we’re using passing objects to
methods, creating Objects with in method and
returning objects from within method.
➢ Higher-Order Functions do to functions what methods
did to objects.
➢ With Higher-Order Functions we can:-
○ Pass Functions-to-Functions.
○ Create Functions-within-Functions.
○ Return Functions-from-Functions.
Higher-Order Functions
➢ Examples:
Effective Final Variable
➢ Effective final variables whose values is never changed
after initialized. Imagine Adding a ‘final’ modifier to
variable declaration.
➢ Example:-
Lexical-Scoping
➢ Lexical-Scoping is the way to declare, specific-scope
of variables and it is only accessible with in that
region.
➢ Two Types Of Lexical Scope.
○ Static Lexical-Scope.
○ Dynamic Lexical-Scope.
➢ Static Lexical-Scope:- The Scope of variable is
declare at compile phase.
Lexical-Scoping
➢ Dynamic Lexical-Scope:- In this, First look for a
local definition of a variable. If isn’t find, we look up
the calling stack for a definition.
➢ Example:-
Method-References
➢ Method References gives you compact, easy-to-read lambda
expressions for method that already have a name.
➢ Example:
() -> “string”.length();
TO
String::length;
➢ There are FOUR types of method reference:-
○ Reference to a static method.
○ Reference to an instance method of a particular object.
○ Reference to an instance method of an arbitrary object
of a particular type.
○ Reference to a constructor.
Method-References
➢ Example:-
➢ Method Reference Lambda Translation:-
Internal-Iterators
➢ The iteration control by iterator not by user.
➢ In this, user pass only the expression, that apply on
our Collection or Data-Structures.
➢ User only need to concentrate on Business logic.
➢ Example:-
External-Iterators
➢ The iteration control by User manual.
Stream’s Common Operations
➢ A Stream is a tool for building up complex operations on
collections using functional approach.
➢ The streams are act as a commands in unix operating
system, in which one command output is input of another
command.
➢ Stream create pipeline for performing operations. These
pipeline is also perform as parallel.
➢ Streams are also deal which Primitives type. But only with
‘int’, ‘long’ and ‘double’.
➢ Java 8 Steam provide ome special interfaces for primitive
types as follow
○ LongStream
○ IntStream
○ DoubleStream
Stream’s Common Operations
➢ Stream is divided into 3 parts:-
○ Declaration
○ Intermediate
○ Termination
➢ Example:-
Stream’s Common Operations
➢ Stream Intermediate Operations are lazily loading. Without
Termination Operation, the Intermediate operation not
perform any action. When termination operation found the
intermediate operation perform task.
➢ There are lots of Intermediate and Termination
operations, but some important we discuss as follow:-
○ filter(Predicated<? super T> predicate)
○ map(Function<? super T, ? extends R> mapper)
○ flatMap(Function<? super T, ? extends Stream<? super
R>> mapper)
○ forEach(Consumer<? super T> action)
○ peek(Consumer<? super T> action)
○ reduce(BinaryOperator<T> accumulator)
Stream’s Common Operations
➢ Stream<T> filter(Predicated<? super T> predicate);
filter build up the Stream recipe, but don’t force this recipe
to be used. They provide lazy behaviour.
Example:
Stream’s Common Operations
➢ <R> Stream<R> map(Function<? super T, ? extends R>
mapper);
map If we want to convert one type of value to another type,
map gives you the way “Apply Function to a Stream of values,
producing another stream of the new values”.
Example:
Stream’s Common Operations
➢ <R> Stream<R> flatMap(Function<? super T, ? extends
Stream<? super R>> mapper);
flatMap If we have multiple Streams of same type, and we need
to concat all the streams together and return one common
Stream, Then flatmap provide the way concatenates all the
stream together
Example:
Stream’s Common Operations
➢ void forEach(Consumer<? super T> action);
forEach It is a Terminal Operation, perform an action for each
element of the stream. The behaviour of this operation is
explicitly nondeterministic.
Example:
Stream’s Common Operations
➢ Stream<T> peek(Consumer<? super T> action);
peek, It is an Intermediate Operation, performing an provided
action on each element as elements are consumed from the
resulting stream.
Example:
Stream’s Common Operations
➢ Stream<T> reduce(BinaryOperator<T> accumulator);
➢reduce It is based on reduction operation, take a
sequence of input elements and combine them into single
summary result by repeated application of a combining
operation such as :-
○ Finding the sum.
○ Maximum of set of numbers.
○ Accumulating elements into a list.
➢ reduce, Operation Follows reduce pattern
Stream’s Common Operations
➢Now we solve the previous problem with the help of reduce
Operation in Stream. This is Terminal Operation.
Example:
Stream’s Collectors
➢ Java 8 Streams have rich of collectors, which provide some
interesting operations perform on collections, like in sql
queries group by, order by etc.
➢ Today we discuss some important collectors :-
○ collect(Collector<? super T, A, R> collector);
○ toList(), toSet() and toMap();
○ toCollection(Supplier<C> collectionFactory);
○ maxBy, minBy and averagingInt(ToIntFunction<? super
T> mapper);
○ partitioningBy(Predicate<? super T> preidicate);
○ groupingBy(Function<? super T, ? extends K>
classifier);
○ joining(CharSequence delimiter, CharSequence prefix,
CharSequence suffix);
Stream’s Collectors
➢ <R, A> R collect(Collector<? super T, A, R> collector);
➢ The Method is a reduce operation that’s useful for
transforming the collection into another form, often a
mutable collection.
➢ This method can perform parallel additions, as appropriate,
into different sublists, and then merge them in a thread-
safe manner into a large list.
➢ This is a Terminal Operation.
➢ The version of collect method accept Collector object
and Java provide us Collectors Utility class, which have
several utility methods, used for generate lists, set and
map. Methods as follow:-
○ toList();
○ toSet();
○ toMap();
Stream’s Collectors
➢ <T> Collector<T, ?, List<T>> toList();
➢ The Method return the List that accumulates the input
element into a new List. There is no guarantees on the
type, mutability, serializability or thread-safety of the
List return.
➢ There is no-guarantee it produce the implementation of
ArrayList or other. If we need Basic Collections
implementation use toCollection() method.
Stream’s Collectors
➢ <T> Collector<T, ?, Set<T>> toSet();
➢ The Method return the Set that accumulates the input
element into a new Set. There is no guarantees on the
type, mutability, serializability or thread-safety of the
List return.
➢ There is no-guarantee it produce the implementation of
HashSet or other. If we need Basic Collections
implementation use toCollection() method.
Stream’s Collectors
➢ <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<?
super T, ? extends K> keyMapper, Function<? super T, ?
extends K> valueMapper);
➢ The Method return the Map whose keys and values are the
result of applying the provided mapping functions to the
input element.
➢ If the mapped keys contain duplicates an
IllegalStateException is thrown when the collection
operation is performed.
Stream’s Collectors
➢ <T> Collector<T, ?, Optional<T>> maxBy(Comparator<?
super T> comparator);
➢ Produces the maximal element from given stream,
according to given Comparator and return Optional Object.
Stream’s Collectors
➢ <T> Collector<T, ?, Double> minBy(ToIntFunction<? super
T> mapper);
➢ Produces the arithmetic-mean of an integer-valued function
applied to the input elements. If no element are present,
result is 0.
Stream’s Collectors
➢ <T> Collector<T, ?, Map<Boolean, List<T>>>
partitioningBy(Predicated<? super T> predicate);
➢ This is a collector that takes a stream and partitions its
content into two groups.
➢ It uses a predicate to determine whether an element
should be a part of true group or the false group and
returns a Map from Boolean to a List of values.
Stream’s Collectors
➢ <T, K> Collector<T, ?, Map<K, List<T>>>
groupingBy(Function<? super T, ? extends K>
classifier);
➢ This functions map element to some Key type K.
Stream’s Collectors
➢ <T, K> Collector<CharSequence, ?, String>
joining(CharSequence delimiter);
➢ This functions concat the input elements, separated by
specify delimiter.
Optional Class
➢ Null is a EVIL
➢ Tony Hoare wrote about null “I call it my billion-dollar
mistake. It was the invention of the null reference in 1965. I
couldn’t resist the temptation to put in a null reference, simply
because it was easy to implement. “
➢ The alternative from functional programming is using a
Option Type, That can contain some value or not.
➢ The Optional Class includes methods to explicitly deal with
cases where a value is present or absent.
➢ Advantage of Optional Class forces to think about the case
when value is not present.
Optional Class
Optional Class
➢ Following are the operations we perform with Optional:-
○ Creating Optional Object
○ Do Something if value is present.
○ Default values and actions.
○ Rejecting Certain values using the filter method.
○ Extracting the transform values using the map method.
○ Cascading the Optional object using the flatMap
method.
➢ The above method we discuss filter, map and flatMap
are not stream methods, they are itself optional class
methods. For further methods refer Java 8 API docs.
Leftover: The Important Topics We Didn’t Cover
1. Method Handlers
2. Default Methods And Static Methods In
Interface.
3. Java 8 Date API.
4. InvokeDynamic.
5. Concurrency In Lambda’s.
6. Parallel Streams.
7. Design And Architect Principals.
8. Code Refactoring.
9. Custom Collectors.
10.Deep Dive in Optional Class
References
➢ Special Thanks to Richard Warburton for “Java 8
lambdas”.
➢ Venkat Subramaniam “Functional Programming In
Java”
➢ Oracle Java API Docs
➢ Raoul-Gabriel Urma “Tierd Of null Pinter Exception”
(http://www.oracle.com/technetwork/articles/java/j
ava8-optional-2175753.html)
Any Many More Like Dzone, StackOverflow etc.

Contenu connexe

Tendances

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday lifeAndrea Iacono
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 

Tendances (20)

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 

En vedette

X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009Frank
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)VLSI SYSTEM Design
 
1 java - data type
1  java - data type1  java - data type
1 java - data typevinay arora
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsRasan Samarasinghe
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State MachineKnoldus Inc.
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and DesignRiazAhmad786
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignMotaz Saad
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAMKnoldus Inc.
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 

En vedette (15)

Graph Database Using Neo4J
Graph Database Using Neo4JGraph Database Using Neo4J
Graph Database Using Neo4J
 
X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
 
1 java - data type
1  java - data type1  java - data type
1 java - data type
 
Jnp
JnpJnp
Jnp
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State Machine
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and Design
 
Structured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and DesignStructured Vs, Object Oriented Analysis and Design
Structured Vs, Object Oriented Analysis and Design
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 

Similaire à Java 8 Streams And Common Operations By Harmeet Singh(Taara)

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
Java 8
Java 8Java 8
Java 8vpulec
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flinkRenato Guimaraes
 
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
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsKevin Webber
 
OGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's ViewOGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's ViewBartosz Dobrzelecki
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Java High Level Stream API
Java High Level Stream APIJava High Level Stream API
Java High Level Stream APIApache Apex
 
Important React Hooks
Important React HooksImportant React Hooks
Important React HooksKnoldus Inc.
 

Similaire à Java 8 Streams And Common Operations By Harmeet Singh(Taara) (20)

Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
java8
java8java8
java8
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Java 8
Java 8Java 8
Java 8
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Java 8
Java 8Java 8
Java 8
 
Hot Streaming Java
Hot Streaming JavaHot Streaming Java
Hot Streaming Java
 
Lambda.pdf
Lambda.pdfLambda.pdf
Lambda.pdf
 
Java 8
Java 8Java 8
Java 8
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flink
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
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
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
OGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's ViewOGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's View
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Java High Level Stream API
Java High Level Stream APIJava High Level Stream API
Java High Level Stream API
 
Important React Hooks
Important React HooksImportant React Hooks
Important React Hooks
 

Dernier

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 

Dernier (20)

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 

Java 8 Streams And Common Operations By Harmeet Singh(Taara)

  • 1. Java 8 Streams & Common Operations By Harmeet Singh(Taara) (Java EE Developer) Email: harmeetsingh.0013@gmail.com Blog: http://harmeetsingh13.blogspot.in Skype: harmeetsingh0013 Contact: Via Email or Skype
  • 2. Contents ➢ Introduction ➢ High-Order Functions ➢ Effective Final Variables ➢ Lexical-Scoping ➢ Method References ➢ Internal-Iterators ➢ External-Iterators ➢ Stream’s Common’s Operation ➢ Stream’s Collectors ➢ Optional Class ➢ Leftover: The Things We Didn’t Cover
  • 3. Acknowledgment ➢ Special Thanks To My Parents. ➢ Thanks To All, Who Support Me or Not. ➢ Dedicated To My Teacher “Mr. Kapil Sakhuja” ➢ Thanks To Insonix.
  • 4. Introduction Today, We cover Java 8 Stream API’s for remove some ‘Boilerplate Code’ from our daily programming. In Java, Some time we need to write some common practices with our collections for fetching the elements and do some operations. This make’s our code dirty. Java 8 Streams provide some powerful operations for our collections libraries. It is basically perform operation like SQL queries on java collections. (Download Examples : https://github.com/harmeetsingh0013/Java8-Streams- Examples.git)
  • 5. Higher-Order Functions ➢ In OO-Programming we’re using passing objects to methods, creating Objects with in method and returning objects from within method. ➢ Higher-Order Functions do to functions what methods did to objects. ➢ With Higher-Order Functions we can:- ○ Pass Functions-to-Functions. ○ Create Functions-within-Functions. ○ Return Functions-from-Functions.
  • 7. Effective Final Variable ➢ Effective final variables whose values is never changed after initialized. Imagine Adding a ‘final’ modifier to variable declaration. ➢ Example:-
  • 8. Lexical-Scoping ➢ Lexical-Scoping is the way to declare, specific-scope of variables and it is only accessible with in that region. ➢ Two Types Of Lexical Scope. ○ Static Lexical-Scope. ○ Dynamic Lexical-Scope. ➢ Static Lexical-Scope:- The Scope of variable is declare at compile phase.
  • 9. Lexical-Scoping ➢ Dynamic Lexical-Scope:- In this, First look for a local definition of a variable. If isn’t find, we look up the calling stack for a definition. ➢ Example:-
  • 10. Method-References ➢ Method References gives you compact, easy-to-read lambda expressions for method that already have a name. ➢ Example: () -> “string”.length(); TO String::length; ➢ There are FOUR types of method reference:- ○ Reference to a static method. ○ Reference to an instance method of a particular object. ○ Reference to an instance method of an arbitrary object of a particular type. ○ Reference to a constructor.
  • 11. Method-References ➢ Example:- ➢ Method Reference Lambda Translation:-
  • 12. Internal-Iterators ➢ The iteration control by iterator not by user. ➢ In this, user pass only the expression, that apply on our Collection or Data-Structures. ➢ User only need to concentrate on Business logic. ➢ Example:-
  • 13. External-Iterators ➢ The iteration control by User manual.
  • 14. Stream’s Common Operations ➢ A Stream is a tool for building up complex operations on collections using functional approach. ➢ The streams are act as a commands in unix operating system, in which one command output is input of another command. ➢ Stream create pipeline for performing operations. These pipeline is also perform as parallel. ➢ Streams are also deal which Primitives type. But only with ‘int’, ‘long’ and ‘double’. ➢ Java 8 Steam provide ome special interfaces for primitive types as follow ○ LongStream ○ IntStream ○ DoubleStream
  • 15. Stream’s Common Operations ➢ Stream is divided into 3 parts:- ○ Declaration ○ Intermediate ○ Termination ➢ Example:-
  • 16. Stream’s Common Operations ➢ Stream Intermediate Operations are lazily loading. Without Termination Operation, the Intermediate operation not perform any action. When termination operation found the intermediate operation perform task. ➢ There are lots of Intermediate and Termination operations, but some important we discuss as follow:- ○ filter(Predicated<? super T> predicate) ○ map(Function<? super T, ? extends R> mapper) ○ flatMap(Function<? super T, ? extends Stream<? super R>> mapper) ○ forEach(Consumer<? super T> action) ○ peek(Consumer<? super T> action) ○ reduce(BinaryOperator<T> accumulator)
  • 17. Stream’s Common Operations ➢ Stream<T> filter(Predicated<? super T> predicate); filter build up the Stream recipe, but don’t force this recipe to be used. They provide lazy behaviour. Example:
  • 18. Stream’s Common Operations ➢ <R> Stream<R> map(Function<? super T, ? extends R> mapper); map If we want to convert one type of value to another type, map gives you the way “Apply Function to a Stream of values, producing another stream of the new values”. Example:
  • 19. Stream’s Common Operations ➢ <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? super R>> mapper); flatMap If we have multiple Streams of same type, and we need to concat all the streams together and return one common Stream, Then flatmap provide the way concatenates all the stream together Example:
  • 20. Stream’s Common Operations ➢ void forEach(Consumer<? super T> action); forEach It is a Terminal Operation, perform an action for each element of the stream. The behaviour of this operation is explicitly nondeterministic. Example:
  • 21. Stream’s Common Operations ➢ Stream<T> peek(Consumer<? super T> action); peek, It is an Intermediate Operation, performing an provided action on each element as elements are consumed from the resulting stream. Example:
  • 22. Stream’s Common Operations ➢ Stream<T> reduce(BinaryOperator<T> accumulator); ➢reduce It is based on reduction operation, take a sequence of input elements and combine them into single summary result by repeated application of a combining operation such as :- ○ Finding the sum. ○ Maximum of set of numbers. ○ Accumulating elements into a list. ➢ reduce, Operation Follows reduce pattern
  • 23. Stream’s Common Operations ➢Now we solve the previous problem with the help of reduce Operation in Stream. This is Terminal Operation. Example:
  • 24. Stream’s Collectors ➢ Java 8 Streams have rich of collectors, which provide some interesting operations perform on collections, like in sql queries group by, order by etc. ➢ Today we discuss some important collectors :- ○ collect(Collector<? super T, A, R> collector); ○ toList(), toSet() and toMap(); ○ toCollection(Supplier<C> collectionFactory); ○ maxBy, minBy and averagingInt(ToIntFunction<? super T> mapper); ○ partitioningBy(Predicate<? super T> preidicate); ○ groupingBy(Function<? super T, ? extends K> classifier); ○ joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix);
  • 25. Stream’s Collectors ➢ <R, A> R collect(Collector<? super T, A, R> collector); ➢ The Method is a reduce operation that’s useful for transforming the collection into another form, often a mutable collection. ➢ This method can perform parallel additions, as appropriate, into different sublists, and then merge them in a thread- safe manner into a large list. ➢ This is a Terminal Operation. ➢ The version of collect method accept Collector object and Java provide us Collectors Utility class, which have several utility methods, used for generate lists, set and map. Methods as follow:- ○ toList(); ○ toSet(); ○ toMap();
  • 26. Stream’s Collectors ➢ <T> Collector<T, ?, List<T>> toList(); ➢ The Method return the List that accumulates the input element into a new List. There is no guarantees on the type, mutability, serializability or thread-safety of the List return. ➢ There is no-guarantee it produce the implementation of ArrayList or other. If we need Basic Collections implementation use toCollection() method.
  • 27. Stream’s Collectors ➢ <T> Collector<T, ?, Set<T>> toSet(); ➢ The Method return the Set that accumulates the input element into a new Set. There is no guarantees on the type, mutability, serializability or thread-safety of the List return. ➢ There is no-guarantee it produce the implementation of HashSet or other. If we need Basic Collections implementation use toCollection() method.
  • 28. Stream’s Collectors ➢ <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends K> valueMapper); ➢ The Method return the Map whose keys and values are the result of applying the provided mapping functions to the input element. ➢ If the mapped keys contain duplicates an IllegalStateException is thrown when the collection operation is performed.
  • 29. Stream’s Collectors ➢ <T> Collector<T, ?, Optional<T>> maxBy(Comparator<? super T> comparator); ➢ Produces the maximal element from given stream, according to given Comparator and return Optional Object.
  • 30. Stream’s Collectors ➢ <T> Collector<T, ?, Double> minBy(ToIntFunction<? super T> mapper); ➢ Produces the arithmetic-mean of an integer-valued function applied to the input elements. If no element are present, result is 0.
  • 31. Stream’s Collectors ➢ <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicated<? super T> predicate); ➢ This is a collector that takes a stream and partitions its content into two groups. ➢ It uses a predicate to determine whether an element should be a part of true group or the false group and returns a Map from Boolean to a List of values.
  • 32. Stream’s Collectors ➢ <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier); ➢ This functions map element to some Key type K.
  • 33. Stream’s Collectors ➢ <T, K> Collector<CharSequence, ?, String> joining(CharSequence delimiter); ➢ This functions concat the input elements, separated by specify delimiter.
  • 34. Optional Class ➢ Null is a EVIL ➢ Tony Hoare wrote about null “I call it my billion-dollar mistake. It was the invention of the null reference in 1965. I couldn’t resist the temptation to put in a null reference, simply because it was easy to implement. “ ➢ The alternative from functional programming is using a Option Type, That can contain some value or not. ➢ The Optional Class includes methods to explicitly deal with cases where a value is present or absent. ➢ Advantage of Optional Class forces to think about the case when value is not present.
  • 36. Optional Class ➢ Following are the operations we perform with Optional:- ○ Creating Optional Object ○ Do Something if value is present. ○ Default values and actions. ○ Rejecting Certain values using the filter method. ○ Extracting the transform values using the map method. ○ Cascading the Optional object using the flatMap method. ➢ The above method we discuss filter, map and flatMap are not stream methods, they are itself optional class methods. For further methods refer Java 8 API docs.
  • 37. Leftover: The Important Topics We Didn’t Cover 1. Method Handlers 2. Default Methods And Static Methods In Interface. 3. Java 8 Date API. 4. InvokeDynamic. 5. Concurrency In Lambda’s. 6. Parallel Streams. 7. Design And Architect Principals. 8. Code Refactoring. 9. Custom Collectors. 10.Deep Dive in Optional Class
  • 38. References ➢ Special Thanks to Richard Warburton for “Java 8 lambdas”. ➢ Venkat Subramaniam “Functional Programming In Java” ➢ Oracle Java API Docs ➢ Raoul-Gabriel Urma “Tierd Of null Pinter Exception” (http://www.oracle.com/technetwork/articles/java/j ava8-optional-2175753.html) Any Many More Like Dzone, StackOverflow etc.