SlideShare a Scribd company logo
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.

More Related Content

What's hot

Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
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
Takipi
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
Mark Harrison
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii 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
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
Oleg Tsal-Tsalko
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
 

What's hot (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
 

Viewers also liked

Graph Database Using Neo4J
Graph Database Using Neo4JGraph Database Using Neo4J
Graph Database Using Neo4J
Harmeet Singh(Taara)
 
X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009
Frank
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
Arif 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, constructor
Shivam 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 type
vinay arora
 
Jnp
JnpJnp
Jnp
hj43us
 
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 basics
Rasan Samarasinghe
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State Machine
Knoldus Inc.
 
Object-Oriented Analysis and Design
Object-Oriented Analysis and DesignObject-Oriented Analysis and Design
Object-Oriented Analysis and Design
RiazAhmad786
 
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
Motaz Saad
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
Knoldus Inc.
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and DesignHaitham El-Ghareeb
 

Viewers also liked (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
 

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

Java 8 streams
Java 8 streams Java 8 streams
Java 8 streams
Srinivasan Raghvan
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
(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
Nico Ludwig
 
Java 8
Java 8Java 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
IndicThreads
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
Hot Streaming Java
Hot Streaming JavaHot Streaming Java
Hot Streaming Java
nick_maiorano
 
Lambda.pdf
Lambda.pdfLambda.pdf
Lambda.pdf
ManishWalia18
 
Java 8
Java 8Java 8
Java 8vpulec
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
Stream processing - Apache flink
Stream processing - Apache flinkStream processing - Apache flink
Stream processing - Apache flink
Renato Guimaraes
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
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
Jö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 Streams
Kevin 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 View
Bartosz 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_ii
Nico Ludwig
 
Java High Level Stream API
Java High Level Stream APIJava High Level Stream API
Java High Level Stream API
Apache Apex
 
Important React Hooks
Important React HooksImportant React Hooks
Important React Hooks
Knoldus Inc.
 

Similar to 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
 

Recently uploaded

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 

Recently uploaded (20)

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 

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.