SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Introduction to Java 8Introduction to Java 8
Manish Mishra,
Software Consultant,
Knoldus Software, LLP
Manish Mishra,
Software Consultant,
Knoldus Software, LLP
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
What is Lambda
Lambda is an anonymous function which can
be passed around in a concise way.
Lambda Expressions: An example
How about sorting a list of Apples?
Lambda Expressions: An example
How about sorting a list of Apples?
To sort any object in Java, we need to
understand the Comparator Interface.
Lambda Expressions: An example
How about sorting a list of Apples?
To sort any Object in Java, we need to
implement the Comparator Interface, which
defines logic for: How to order two objects.
Lambda Expressions: An example
How about sorting a list of Apples?
Comparator<Apple> byWeight = new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight());
}
};
Lambda Expressions: An example
How about sorting a list of Apples?
Comparator<Apple> byWeight1 = (Apple a1, Apple a2) ->
a1.getWeight().compareTo(a2.getWeight());
Constructing Lambda
A lambda expression is composed of three
parts:
A list of parameters:
(Apple a1, Apple a2)
Constructing Lambda
A lambda expression is composed of three
parts:
A list of parameters, an arrow:
(Apple a1, Apple a2) ->
Constructing Lambda
A lambda expression is composed of three
parts:
A list of parameters, an arrow and a body:
(Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
Valid Lambda Expressions
Here are some examples of valid lambda
expressions:
● (String anyString) -> anyString.length()
Valid Lambda Expressions
Here are some examples of valid lambda
expressions:
● (String anyString) -> anyString.length()
● (Apple a) -> a.getWeight() > 150
Valid Lambda Expressions
Here are some examples of valid lambda
expressions:
● (String anyString) -> anyString.length()
● (Apple a) -> a.getWeight() > 150
● () -> 47
Valid Lambda Expressions
Here are some examples of valid lambda expressions:
● (String anyString) -> anyString.length()
● (Apple a) -> a.getWeight() > 150
● () -> 47
● (int a, int b) -> {
System.out.println("Sqaure:");
System.out.println(a*b);
}
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
Functional Interfaces
A functional interface contains only a one
abstract method.
In Java 8 annotations, It is annotated as
@FunctionalInterface
Functional Interfaces: Examples
● Runnable is a functional interface with an
abstract method run().
● Comparator<T> is a functional interface with
an abstract method compareTo()
Why functional Interface
A functional interface let you describe a
lambda function. In other words,
Lambda expressions are used to instantiate a
functional interface.
@FunctionalInterface
interface Calculation {
int calculate(int a, int b);
}
Why functional Interface
A functional interface let you describe a lambda
function. In other words,
Lambda expressions are used to instantiate a
functional interface.
@FunctionalInterface
interface Calculation {
int calculate(int a, int b);
}
Calculation addition = (Int a, Int b) → (a+b)
Function Descriptor
The signature of an abstract method of a
functional interface is called function
descriptor.
@FunctionalInterface
interface Calculation {
int calculate(int a, int b);
}
Function Descriptor: Example
The signature of an abstract method of a
functional interface is called function
descriptor.
@FunctionalInterface
interface Calculation {
int calculate(int a, int b);
}
Calculation addition = (Int a, Int b) → (a+b)
Function Descriptor: Example
The signature of an abstract method of a
functional interface is called function
descriptor.
@FunctionalInterface
interface Calculation {
int calculate(int a, int b);
}
Calculation subtraction = (Int a, Int b) → (a-b)
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
Interface's default methods
An interface can declare a method and can
provide a default implementation for it.
Interface's default methods
An interface can declare a method and can
provide a default implementation for it.
private interface InterfaceOrTrait{
default String alreadyDone() {
return "Default implementation of method String";
}
}
Why Interface's default methods
● Adding enhancement to language without
hurting the backward compatibility.
Why Interface's default methods
● Adding enhancement to language without hurting the backward compatibility.
● Method for a default situation where any implementing class fails to implement
certain methods in the Interface e.g.
interface Iterator<T> {
boolean hasNext();
T next();
default void remove() {
throw new UnsupportedOperationException();
}
}
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
Method References
● Provides syntax to refer directly to existing
methods
● Can pass existing methods just like lambdas
to functions
● It is better to re use the existing methods
instead of creating lambda expressions for
them.
Method References: Example
Lambda Method reference equivalent
(Apple a) -> a.getWeight() Apple::getWeight
() -> Thread.currentThread().dumpStack() Thread.currentThread()::dumpStack
(str, i) -> str.substring(i) String::substring
(String s) -> System.out.println(s) System.out::println
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
Stream API
Streams are monads which help writing
programs in a declarative way, chaining
multiple operations which are safe and bug
free.
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
Why Streams
● Advantages over Collections
● No Storage
● Laziness-seeking
● Functional in nature
● No Bounds (infinite streams)
● Parallelizable
Streams API: An Example
Comparator<Apple> byWeight = new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight());
}
}
Streams API: An Example
listOfApples.add(new Apple("green",12.0));
listOfApples.add(new Apple("red",12.0));
listOfApples.add(new Apple("green",17.0));
listOfApples.add(new Apple("yellow",12.0));
listOfApples.stream()
.filter( apple -> apple.getColor().equals("green"))
.sorted(byWeight)
.forEach(System.out::println);
Streams API: An Example
listOfApples.add(new Apple("green",12.0));
listOfApples.add(new Apple("red",12.0));
listOfApples.add(new Apple("green",17.0));
listOfApples.add(new Apple("yellow",12.0));
listOfApples.stream()
.filter( apple -> apple.getColor().equals("green"))
.sorted(byWeight)
.forEach(System.out::println);
Streams API: An Example
listOfApples.add(new Apple("green",12.0));
listOfApples.add(new Apple("red",12.0));
listOfApples.add(new Apple("green",17.0));
listOfApples.add(new Apple("yellow",12.0));
listOfApples.stream()
.filter( apple -> apple.getColor().equals("green"))
.sorted(byWeight)
.forEach(System.out::println);
Streams API: An Example
listOfApples.add(new Apple("green",12.0));
listOfApples.add(new Apple("red",12.0));
listOfApples.add(new Apple("green",17.0));
listOfApples.add(new Apple("yellow",12.0));
listOfApples.stream()
.filter( apple -> apple.getColor().equals("green"))
.sorted(byWeight)
.forEach(System.out::println);
Creating Streams
● From a Collections
List<Apple> listOfApples = new ArrayList();
listOfApples.add(new Apple("yellow",12.0));
Stream<Apple> apples = listOfApples.stream()
Creating Streams
● From a Collections
List<Apple> listOfApples = new ArrayList();
listOfApples.add(new Apple("yellow",12.0));
Stream<Apple> apples = listOfApples.stream()
● From Primitive values
Stream<String> wordStream = Stream.of("Value1 ", "Value2", "Value3", "Value4");
Creating Streams
● From a Collections
List<Apple> listOfApples = new ArrayList();
listOfApples.add(new Apple("yellow",12.0));
Stream<Apple> apples = listOfApples.stream()
● From Primitive values
Stream<String> wordStream = Stream.of("Value1 ", "Value2", "Value3", "Value4");
● From An Array
int [] primitives = {2,4,6,8,10};
Stream<String> stream = Arrays.stream(primitives);
Agenda
● Lambda Expressions
● Functional Interfaces
● Default Methods
● Method References
● Streams API
● Why Streams?
● Operations on Streams
Operations on Streams
● Reduction
Double totalWeight = listOfApples.stream().mapToDouble(Apple::getWeight).sum();
Double totalReducedWeight =
listOfApples.stream().mapToDouble(Apple::getWeight).reduce(0,(a,b) -> a+b);
Operations on Streams
● Reduction
Double totalWeight = listOfApples.stream().mapToDouble(Apple::getWeight).sum();
Double totalReducedWeight =
listOfApples.stream().mapToDouble(Apple::getWeight).reduce(0,(a,b) -> a+b);
The reduce operation in this example takes two arguments:
● identity: The identity element is both the initial value of the reduction
● accumulator: The accumulator function takes two parameters: a partial result of the reduction
and the next element of the stream
Operations on Streams
● Grouping
Map<String, List<Apple>> applesByColor =
listOfApples.stream().collect(Collectors.groupingBy(Apple::getColor));
The above method uses groupingBy method to join the apples by color and returns a Map of
type <String, List<Apple>
Operations on Streams
● Stats
DoubleSummaryStatistics weightStats =
listOfApples.stream().mapToDouble(Apple::getWeight).summaryStatistics();
System.out.println("The max of Double" + weightStats.getAverage());
System.out.println("The min of Double" + weightStats.getMin());
System.out.println("The max of Double" + weightStats.getMax());
The DoubleSummaryStatistics class contain the stats like count, max, min etc.
References
● Java 8 In Action:
Book by: Mario-Fusco,Alan Mycroft, Raoul-
Gabriel Urma
Thank YouThank You

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java collection
Java collectionJava collection
Java collection
 
Java 8 - An Overview
Java 8 - An OverviewJava 8 - An Overview
Java 8 - An Overview
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Java collections
Java collectionsJava collections
Java collections
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 

Andere mochten auch

Walk-through: Amazon ECS
Walk-through: Amazon ECSWalk-through: Amazon ECS
Walk-through: Amazon ECSKnoldus Inc.
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JSKnoldus Inc.
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJsKnoldus Inc.
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async LibraryKnoldus Inc.
 
Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionKnoldus Inc.
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomKnoldus Inc.
 
String interpolation
String interpolationString interpolation
String interpolationKnoldus Inc.
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaKnoldus Inc.
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala MacrosKnoldus Inc.
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to QuillKnoldus Inc.
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill TemplatesKnoldus Inc.
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZKnoldus Inc.
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout JsKnoldus Inc.
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in ScalaKnoldus Inc.
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testingKnoldus Inc.
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in JavascriptKnoldus Inc.
 

Andere mochten auch (20)

Walk-through: Amazon ECS
Walk-through: Amazon ECSWalk-through: Amazon ECS
Walk-through: Amazon ECS
 
Tic tac toe
Tic tac toeTic tac toe
Tic tac toe
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An Introduction
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
 
String interpolation
String interpolationString interpolation
String interpolation
 
Kanban
KanbanKanban
Kanban
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
An Introduction to Quill
An Introduction to QuillAn Introduction to Quill
An Introduction to Quill
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
ANTLR4 and its testing
ANTLR4 and its testingANTLR4 and its testing
ANTLR4 and its testing
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 

Ähnlich wie Introduction to Java 8

What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8Dian Aditya
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
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)
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New featuresSon Nguyen
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
Project Lambda: Evolution of Java
Project Lambda: Evolution of JavaProject Lambda: Evolution of Java
Project Lambda: Evolution of JavaCan Pekdemir
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8Dinesh Pathak
 
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
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8Jobaer Chowdhury
 

Ähnlich wie Introduction to Java 8 (20)

Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java8
Java8Java8
Java8
 
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
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Java 8
Java 8Java 8
Java 8
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
java8
java8java8
java8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Project Lambda: Evolution of Java
Project Lambda: Evolution of JavaProject Lambda: Evolution of Java
Project Lambda: Evolution of Java
 
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
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Java 8
Java 8Java 8
Java 8
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
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
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 

Mehr von Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

Mehr von Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Kürzlich hochgeladen

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Kürzlich hochgeladen (20)

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
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
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Introduction to Java 8

  • 1. Introduction to Java 8Introduction to Java 8 Manish Mishra, Software Consultant, Knoldus Software, LLP Manish Mishra, Software Consultant, Knoldus Software, LLP
  • 2. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 3. What is Lambda Lambda is an anonymous function which can be passed around in a concise way.
  • 4. Lambda Expressions: An example How about sorting a list of Apples?
  • 5. Lambda Expressions: An example How about sorting a list of Apples? To sort any object in Java, we need to understand the Comparator Interface.
  • 6. Lambda Expressions: An example How about sorting a list of Apples? To sort any Object in Java, we need to implement the Comparator Interface, which defines logic for: How to order two objects.
  • 7. Lambda Expressions: An example How about sorting a list of Apples? Comparator<Apple> byWeight = new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { return o1.getWeight().compareTo(o2.getWeight()); } };
  • 8. Lambda Expressions: An example How about sorting a list of Apples? Comparator<Apple> byWeight1 = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
  • 9. Constructing Lambda A lambda expression is composed of three parts: A list of parameters: (Apple a1, Apple a2)
  • 10. Constructing Lambda A lambda expression is composed of three parts: A list of parameters, an arrow: (Apple a1, Apple a2) ->
  • 11. Constructing Lambda A lambda expression is composed of three parts: A list of parameters, an arrow and a body: (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
  • 12. Valid Lambda Expressions Here are some examples of valid lambda expressions: ● (String anyString) -> anyString.length()
  • 13. Valid Lambda Expressions Here are some examples of valid lambda expressions: ● (String anyString) -> anyString.length() ● (Apple a) -> a.getWeight() > 150
  • 14. Valid Lambda Expressions Here are some examples of valid lambda expressions: ● (String anyString) -> anyString.length() ● (Apple a) -> a.getWeight() > 150 ● () -> 47
  • 15. Valid Lambda Expressions Here are some examples of valid lambda expressions: ● (String anyString) -> anyString.length() ● (Apple a) -> a.getWeight() > 150 ● () -> 47 ● (int a, int b) -> { System.out.println("Sqaure:"); System.out.println(a*b); }
  • 16. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 17. Functional Interfaces A functional interface contains only a one abstract method. In Java 8 annotations, It is annotated as @FunctionalInterface
  • 18. Functional Interfaces: Examples ● Runnable is a functional interface with an abstract method run(). ● Comparator<T> is a functional interface with an abstract method compareTo()
  • 19. Why functional Interface A functional interface let you describe a lambda function. In other words, Lambda expressions are used to instantiate a functional interface. @FunctionalInterface interface Calculation { int calculate(int a, int b); }
  • 20. Why functional Interface A functional interface let you describe a lambda function. In other words, Lambda expressions are used to instantiate a functional interface. @FunctionalInterface interface Calculation { int calculate(int a, int b); } Calculation addition = (Int a, Int b) → (a+b)
  • 21. Function Descriptor The signature of an abstract method of a functional interface is called function descriptor. @FunctionalInterface interface Calculation { int calculate(int a, int b); }
  • 22. Function Descriptor: Example The signature of an abstract method of a functional interface is called function descriptor. @FunctionalInterface interface Calculation { int calculate(int a, int b); } Calculation addition = (Int a, Int b) → (a+b)
  • 23. Function Descriptor: Example The signature of an abstract method of a functional interface is called function descriptor. @FunctionalInterface interface Calculation { int calculate(int a, int b); } Calculation subtraction = (Int a, Int b) → (a-b)
  • 24. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 25. Interface's default methods An interface can declare a method and can provide a default implementation for it.
  • 26. Interface's default methods An interface can declare a method and can provide a default implementation for it. private interface InterfaceOrTrait{ default String alreadyDone() { return "Default implementation of method String"; } }
  • 27. Why Interface's default methods ● Adding enhancement to language without hurting the backward compatibility.
  • 28. Why Interface's default methods ● Adding enhancement to language without hurting the backward compatibility. ● Method for a default situation where any implementing class fails to implement certain methods in the Interface e.g. interface Iterator<T> { boolean hasNext(); T next(); default void remove() { throw new UnsupportedOperationException(); } }
  • 29. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 30. Method References ● Provides syntax to refer directly to existing methods ● Can pass existing methods just like lambdas to functions ● It is better to re use the existing methods instead of creating lambda expressions for them.
  • 31. Method References: Example Lambda Method reference equivalent (Apple a) -> a.getWeight() Apple::getWeight () -> Thread.currentThread().dumpStack() Thread.currentThread()::dumpStack (str, i) -> str.substring(i) String::substring (String s) -> System.out.println(s) System.out::println
  • 32. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 33. Stream API Streams are monads which help writing programs in a declarative way, chaining multiple operations which are safe and bug free.
  • 34. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 35. Why Streams ● Advantages over Collections ● No Storage ● Laziness-seeking ● Functional in nature ● No Bounds (infinite streams) ● Parallelizable
  • 36. Streams API: An Example Comparator<Apple> byWeight = new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { return o1.getWeight().compareTo(o2.getWeight()); } }
  • 37. Streams API: An Example listOfApples.add(new Apple("green",12.0)); listOfApples.add(new Apple("red",12.0)); listOfApples.add(new Apple("green",17.0)); listOfApples.add(new Apple("yellow",12.0)); listOfApples.stream() .filter( apple -> apple.getColor().equals("green")) .sorted(byWeight) .forEach(System.out::println);
  • 38. Streams API: An Example listOfApples.add(new Apple("green",12.0)); listOfApples.add(new Apple("red",12.0)); listOfApples.add(new Apple("green",17.0)); listOfApples.add(new Apple("yellow",12.0)); listOfApples.stream() .filter( apple -> apple.getColor().equals("green")) .sorted(byWeight) .forEach(System.out::println);
  • 39. Streams API: An Example listOfApples.add(new Apple("green",12.0)); listOfApples.add(new Apple("red",12.0)); listOfApples.add(new Apple("green",17.0)); listOfApples.add(new Apple("yellow",12.0)); listOfApples.stream() .filter( apple -> apple.getColor().equals("green")) .sorted(byWeight) .forEach(System.out::println);
  • 40. Streams API: An Example listOfApples.add(new Apple("green",12.0)); listOfApples.add(new Apple("red",12.0)); listOfApples.add(new Apple("green",17.0)); listOfApples.add(new Apple("yellow",12.0)); listOfApples.stream() .filter( apple -> apple.getColor().equals("green")) .sorted(byWeight) .forEach(System.out::println);
  • 41. Creating Streams ● From a Collections List<Apple> listOfApples = new ArrayList(); listOfApples.add(new Apple("yellow",12.0)); Stream<Apple> apples = listOfApples.stream()
  • 42. Creating Streams ● From a Collections List<Apple> listOfApples = new ArrayList(); listOfApples.add(new Apple("yellow",12.0)); Stream<Apple> apples = listOfApples.stream() ● From Primitive values Stream<String> wordStream = Stream.of("Value1 ", "Value2", "Value3", "Value4");
  • 43. Creating Streams ● From a Collections List<Apple> listOfApples = new ArrayList(); listOfApples.add(new Apple("yellow",12.0)); Stream<Apple> apples = listOfApples.stream() ● From Primitive values Stream<String> wordStream = Stream.of("Value1 ", "Value2", "Value3", "Value4"); ● From An Array int [] primitives = {2,4,6,8,10}; Stream<String> stream = Arrays.stream(primitives);
  • 44. Agenda ● Lambda Expressions ● Functional Interfaces ● Default Methods ● Method References ● Streams API ● Why Streams? ● Operations on Streams
  • 45. Operations on Streams ● Reduction Double totalWeight = listOfApples.stream().mapToDouble(Apple::getWeight).sum(); Double totalReducedWeight = listOfApples.stream().mapToDouble(Apple::getWeight).reduce(0,(a,b) -> a+b);
  • 46. Operations on Streams ● Reduction Double totalWeight = listOfApples.stream().mapToDouble(Apple::getWeight).sum(); Double totalReducedWeight = listOfApples.stream().mapToDouble(Apple::getWeight).reduce(0,(a,b) -> a+b); The reduce operation in this example takes two arguments: ● identity: The identity element is both the initial value of the reduction ● accumulator: The accumulator function takes two parameters: a partial result of the reduction and the next element of the stream
  • 47. Operations on Streams ● Grouping Map<String, List<Apple>> applesByColor = listOfApples.stream().collect(Collectors.groupingBy(Apple::getColor)); The above method uses groupingBy method to join the apples by color and returns a Map of type <String, List<Apple>
  • 48. Operations on Streams ● Stats DoubleSummaryStatistics weightStats = listOfApples.stream().mapToDouble(Apple::getWeight).summaryStatistics(); System.out.println("The max of Double" + weightStats.getAverage()); System.out.println("The min of Double" + weightStats.getMin()); System.out.println("The max of Double" + weightStats.getMax()); The DoubleSummaryStatistics class contain the stats like count, max, min etc.
  • 49. References ● Java 8 In Action: Book by: Mario-Fusco,Alan Mycroft, Raoul- Gabriel Urma