SlideShare una empresa de Scribd logo
1 de 63
JAVA 8
At First Glance
VISION Team - 2015
Agenda
❖ New Features in Java language
➢ Lambda Expression
➢ Functional Interface
➢ Interface’s default and Static Methods
➢ Method References
❖ New Features in Java libraries
➢ Stream API
➢ Date/Time API
Lambda Expression
What is Lambda Expression?
❖ Unnamed block of code (or an unnamed
function) with a list of formal parameters and
a body.
✓ Concise
✓ Anonymous
✓ Function
✓ Passed around
Lambda Expression
Lambda Expression
Why should we care about
Lambda Expression?
Example 1:
Comparator<Person> byAge = new Comparator<Person>(){
public int compare(Person p1, Person p2){
return p1.getAge().compareTo(p2.getAge());
}
};
Lambda Expression
Example 2:
JButton testButton = new JButton("Test Button");
testButton.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ae){
System.out.println(“Hello Anonymous inner class");
}
});
Example 1: with lambda
Comparator<Person> byAge =
(Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
Lambda Expression
Example 2: with lambda
testButton.addActionListener(e -> System.out.println(“Hello
Lambda"));
Lambda Expression
Lambda Syntax
(Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
Lambda Expression
Lambda parameters Lambda body
Arrow
The basic syntax of a lambda is either
(parameters) -> expression
or
(parameters) -> { statements; }
❖ Lambda does not have:
✓ Name
✓ Return type
✓ Throws clause
✓ Type parameters
Lambda Expression
Examples:
1. (String s) -> s.length()
2. (Person p) -> p.getAge() > 20
3. () -> 92
4. (int x, int y) -> x + y
5. (int x, int y) -> {
System.out.println(“Result:”);
System.out.println(x + y);
}
Lambda Expression
Variable scope:
public void printNumber(int x) {
int y = 2;
Runnable r = () -> System.out.println(“Total is:” + (x+y));
new Thread(r).start();
}
Lambda Expression
Free variable: not define in lambda parameters.
Variable scope:
public void printNumber(int x) {
int y = 2;
Runnable r = () ->{System.out.println(“Total is:” + (x+y));
System.out.println(this.toString());};
new Thread(r).start();
}
Not allow:
public void printNumber(int x) {
int y = 2;
Runnable r = () -> {
x++;//compile error
System.out.println(“Total is:” + (x+y))
};
}
Lambda Expression
Where should we use Lambda?
Comparator:
Comparator<Person> byAge =
(Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
Collections.sort(personList, byAge);
Lambda Expression
Listener:
ActionListener listener = e -> System.out.println(“Hello
Lambda")
testButton.addActionListener(listener );
Example:
public void main(String[] args){
(int x, int y) -> System.out.println(x + y);
}
Runnable:
// Anonymous class
Runnable r1 = new Runnable(){
@Override
public void run(){
System.out.println("Hello world one!");
}
};
// Lambda Runnable
Runnable r2 = () -> System.out.println("Hello world two!");
Lambda Expression
Iterator:
List<String> features = Arrays.asList("Lambdas", "Default
Method", "Stream API", "Date and Time API");
//Prior to Java 8 :
for (String feature : features) {
System.out.println(feature);
}
//In Java 8:
Consumer<String> con = n -> System.out.println(n)
features.forEach(con);
Lambda Expression
Demonstration
What is functional interface?
Add text here...
Functional Interface
● New term of Java 8
● A functional interface is an interface with
only one abstract method.
Add text here...
Functional Interface
● Methods from the Object class don’t
count.
Add text here...
Functional Interface
Annotation in Functional
Interface
Add text here...
Functional Interface
● A functional interface can be annotated.
● It’s optional.
Add text here...
Functional Interface
● Show compile error when define more
than one abstract method.
Add text here...
Functional Interface
Functional Interfaces
Toolbox
Add text here...
Functional Interface
● Brand new java.util.function package.
● Rich set of function interfaces.
● 4 categories:
o Supplier
o Consumer
o Predicate
o Function
Add text here...
Functional Interface
● Accept an object and return nothing.
● Can be implemented by lambda
expression.
Add text here...
Consumer Interface
Demonstration
Interface Default and Static
Methods
Add text here...
Interface Default and Static Methods
static <T> Collection<T>
synchronizedCollection(Collection<T
Interface Default and Static Methods
● Advantages:
- No longer need to provide your own companion utility classes. Instead, you
can place static methods in the appropriate interfaces
- Adding methods to an interface without breaking the existing
implementation
java.util.Collections
java.util.Collection
● Extends interface declarations with two new concepts:
- Default methods
- Static methods
Interface Default and Static Methods
[modifier] default | static returnType nameOfMethod (Parameter List) {
// method body
}
● Syntax
Default methods
● Classes implement interface that contains a default method
❏ Not override the default method and will inherit the default method
❏ Override the default method similar to other methods we override in
subclass
❏ Redeclare default method as abstract, which force subclass to override it
Default methods
● Solve the conflict when the same method declare in interface or
class
- Method of Superclasses, if a superclass provides a concrete
method.
- If a superinterface provides a default method, and another
interface supplies a method with the same name and
parameter types (default or not), then you must overriding that
method.
Static methods
● Similar to default methods except that we can’t override
them in the implementation classes
Demonstration
Method References
● Method reference is an important feature related to
lambda expressions. In order to that a method
reference requires a target type context that consists of
a compatible functional interface
Method References
● There are four kinds of method references:
- 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
● Reference to a static method
The syntax: ContainingClass::staticMethodName
Method References
● Reference to an instance method of a particular object
The syntax: containingObject::instanceMethodName
Method References
● Reference to an instance method of an arbitrary object of a
particular type
The syntax: ContainingType::methodName
Method References
● Reference to a constructor
The syntax: ClassName::new
Method References
● Method references as Lambdas Expressions
Syntax Example As Lambda
ClassName::new String::new () -> new String()
Class::staticMethodName String::valueOf (s) -> String.valueOf(s)
object::instanceMethodName x::toString () -> "hello".toString()
Class::instanceMethodName String::toString (s) -> s.toString()
What is a Stream?
Add text here...
Stream
Old Java:
Add text here...
Stream
Add text here...
Stream
Java 8:
❏Not store data
❏Designed for processing data
❏Not reusable
❏Can easily be outputted as arrays or
lists
Add text here...
Stream
1. Build a stream
Add text here...
Stream - How to use
2. Transform stream
3. Collect result
Build streams from collections
List<Dish> dishes = new ArrayList<Dish>();
....(add some Dishes)....
Stream<Dish> stream = dishes.stream();
Add text here...
Stream - build streams
Build streams from arrays
Integer[] integers =
{1, 2, 3, 4, 5, 6, 7, 8, 9};
Stream<Integer> stream = Stream.of(integers);
Add text here...
Stream - build streams
Intermediate operations (return Stream)
❖ filter()
❖ map()
❖ sorted()
❖ ….
Add text here...
Stream - Operations
// get even numbers
Stream<Integer> evenNumbers = stream
.filter(i -> i%2 == 0);
// Now evenNumbers have {2, 4, 6, 8}
Add text here...
Stream - filter()
Terminal operations
❖ forEach()
❖ collect()
❖ match()
❖ ….
Add text here...
Stream - Operations
// get even numbers
evenNumbers.forEach(i ->
System.out.println(i));
/* Console output
* 2
* 4
* 6
* 8
*/
Add text here...
Stream - forEach()
Converting stream to list
List<Integer> numbers =
evenNumbers.collect(Collectors.toList());
Converting stream to array
Integer[] numbers =
evenNumbers.toArray(Integer[]::new);
Add text here...
Stream - Converting to collections
Demonstration
What’s new in Date/Time?
Add text here...
Date / Time
● Why do we need a new Date/Time API?
Add text here...
Date / Time
○ Objects are not immutable
○ Naming
○ Months are zero-based
● LocalDate
Add text here...
Date / Time
○ A LocalDate is a date, with a year,
month, and day of the month
LocalDate today = LocalDate.now();
LocalDate christmas2015 = LocalDate.of(2015, 12, 25);
LocalDate christmas2015 = LocalDate.of(2015,
Month.DECEMBER, 25);
Java 7:
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
Date dt = c.getTime();
Java 8:
LocalDate tomorrow = LocalDate.now().plusDay(1);
Add text here...
Date / Time
● Temporal adjuster
Add text here...
Date / Time
LocalDate nextPayDay = LocalDate.now()
.with(TemporalAdjusters.lastDayOfMonth());
● Create your own adjuster
TemporalAdjuster NEXT_WORKDAY = w -> {
LocalDate result = (LocalDate) w;
do {
result = result.plusDays(1);
} while (result.getDayOfWeek().getValue() >= 6);
return result;
};
LocalDate backToWork = today.with(NEXT_WORKDAY);
Add text here...
Date / Time
For further questions, send to us: hcmc-vision@axonactive.vn
Add text here...
References
❖ Java Platform Standard Edition 8 Documentation,
(http://docs.oracle.com/javase/8/docs/)
❖ Java 8 In Action, Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft.
❖ Beginning Java 8 Language Features, Kishori Sharan.
❖ What’s new in Java 8 - Pluralsight
Add text here...
The End

Más contenido relacionado

La actualidad más candente

Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 

La actualidad más candente (20)

Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Selenium-Locators
Selenium-LocatorsSelenium-Locators
Selenium-Locators
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Generics
GenericsGenerics
Generics
 

Destacado

New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsGanesh Samarthyam
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
Supercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-reactSupercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-reactJohn McClean
 

Destacado (7)

New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Supercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-reactSupercharged java 8 : with cyclops-react
Supercharged java 8 : with cyclops-react
 

Similar a Java 8 presentation

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8Dian Aditya
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hotSergii Maliarov
 
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 findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
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
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 

Similar a Java 8 presentation (20)

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
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
 
Java 8
Java 8Java 8
Java 8
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
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
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java8
Java8Java8
Java8
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
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
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 

Último

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Último (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

Java 8 presentation

  • 1. JAVA 8 At First Glance VISION Team - 2015
  • 2. Agenda ❖ New Features in Java language ➢ Lambda Expression ➢ Functional Interface ➢ Interface’s default and Static Methods ➢ Method References ❖ New Features in Java libraries ➢ Stream API ➢ Date/Time API
  • 3. Lambda Expression What is Lambda Expression?
  • 4. ❖ Unnamed block of code (or an unnamed function) with a list of formal parameters and a body. ✓ Concise ✓ Anonymous ✓ Function ✓ Passed around Lambda Expression
  • 5. Lambda Expression Why should we care about Lambda Expression?
  • 6. Example 1: Comparator<Person> byAge = new Comparator<Person>(){ public int compare(Person p1, Person p2){ return p1.getAge().compareTo(p2.getAge()); } }; Lambda Expression Example 2: JButton testButton = new JButton("Test Button"); testButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae){ System.out.println(“Hello Anonymous inner class"); } });
  • 7. Example 1: with lambda Comparator<Person> byAge = (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge()); Lambda Expression Example 2: with lambda testButton.addActionListener(e -> System.out.println(“Hello Lambda"));
  • 9. (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge()); Lambda Expression Lambda parameters Lambda body Arrow The basic syntax of a lambda is either (parameters) -> expression or (parameters) -> { statements; }
  • 10. ❖ Lambda does not have: ✓ Name ✓ Return type ✓ Throws clause ✓ Type parameters Lambda Expression
  • 11. Examples: 1. (String s) -> s.length() 2. (Person p) -> p.getAge() > 20 3. () -> 92 4. (int x, int y) -> x + y 5. (int x, int y) -> { System.out.println(“Result:”); System.out.println(x + y); } Lambda Expression
  • 12. Variable scope: public void printNumber(int x) { int y = 2; Runnable r = () -> System.out.println(“Total is:” + (x+y)); new Thread(r).start(); } Lambda Expression Free variable: not define in lambda parameters. Variable scope: public void printNumber(int x) { int y = 2; Runnable r = () ->{System.out.println(“Total is:” + (x+y)); System.out.println(this.toString());}; new Thread(r).start(); } Not allow: public void printNumber(int x) { int y = 2; Runnable r = () -> { x++;//compile error System.out.println(“Total is:” + (x+y)) }; }
  • 14. Comparator: Comparator<Person> byAge = (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge()); Collections.sort(personList, byAge); Lambda Expression Listener: ActionListener listener = e -> System.out.println(“Hello Lambda") testButton.addActionListener(listener ); Example: public void main(String[] args){ (int x, int y) -> System.out.println(x + y); }
  • 15. Runnable: // Anonymous class Runnable r1 = new Runnable(){ @Override public void run(){ System.out.println("Hello world one!"); } }; // Lambda Runnable Runnable r2 = () -> System.out.println("Hello world two!"); Lambda Expression
  • 16. Iterator: List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); //Prior to Java 8 : for (String feature : features) { System.out.println(feature); } //In Java 8: Consumer<String> con = n -> System.out.println(n) features.forEach(con); Lambda Expression
  • 18. What is functional interface? Add text here... Functional Interface
  • 19. ● New term of Java 8 ● A functional interface is an interface with only one abstract method. Add text here... Functional Interface
  • 20. ● Methods from the Object class don’t count. Add text here... Functional Interface
  • 21. Annotation in Functional Interface Add text here... Functional Interface
  • 22. ● A functional interface can be annotated. ● It’s optional. Add text here... Functional Interface
  • 23. ● Show compile error when define more than one abstract method. Add text here... Functional Interface
  • 24. Functional Interfaces Toolbox Add text here... Functional Interface
  • 25. ● Brand new java.util.function package. ● Rich set of function interfaces. ● 4 categories: o Supplier o Consumer o Predicate o Function Add text here... Functional Interface
  • 26. ● Accept an object and return nothing. ● Can be implemented by lambda expression. Add text here... Consumer Interface
  • 28. Interface Default and Static Methods Add text here... Interface Default and Static Methods
  • 29. static <T> Collection<T> synchronizedCollection(Collection<T Interface Default and Static Methods ● Advantages: - No longer need to provide your own companion utility classes. Instead, you can place static methods in the appropriate interfaces - Adding methods to an interface without breaking the existing implementation java.util.Collections java.util.Collection ● Extends interface declarations with two new concepts: - Default methods - Static methods
  • 30. Interface Default and Static Methods [modifier] default | static returnType nameOfMethod (Parameter List) { // method body } ● Syntax
  • 31. Default methods ● Classes implement interface that contains a default method ❏ Not override the default method and will inherit the default method ❏ Override the default method similar to other methods we override in subclass ❏ Redeclare default method as abstract, which force subclass to override it
  • 32. Default methods ● Solve the conflict when the same method declare in interface or class - Method of Superclasses, if a superclass provides a concrete method. - If a superinterface provides a default method, and another interface supplies a method with the same name and parameter types (default or not), then you must overriding that method.
  • 33. Static methods ● Similar to default methods except that we can’t override them in the implementation classes
  • 35. Method References ● Method reference is an important feature related to lambda expressions. In order to that a method reference requires a target type context that consists of a compatible functional interface
  • 36. Method References ● There are four kinds of method references: - 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
  • 37. Method References ● Reference to a static method The syntax: ContainingClass::staticMethodName
  • 38. Method References ● Reference to an instance method of a particular object The syntax: containingObject::instanceMethodName
  • 39. Method References ● Reference to an instance method of an arbitrary object of a particular type The syntax: ContainingType::methodName
  • 40. Method References ● Reference to a constructor The syntax: ClassName::new
  • 41. Method References ● Method references as Lambdas Expressions Syntax Example As Lambda ClassName::new String::new () -> new String() Class::staticMethodName String::valueOf (s) -> String.valueOf(s) object::instanceMethodName x::toString () -> "hello".toString() Class::instanceMethodName String::toString (s) -> s.toString()
  • 42. What is a Stream? Add text here... Stream
  • 43. Old Java: Add text here... Stream
  • 45. ❏Not store data ❏Designed for processing data ❏Not reusable ❏Can easily be outputted as arrays or lists Add text here... Stream
  • 46. 1. Build a stream Add text here... Stream - How to use 2. Transform stream 3. Collect result
  • 47. Build streams from collections List<Dish> dishes = new ArrayList<Dish>(); ....(add some Dishes).... Stream<Dish> stream = dishes.stream(); Add text here... Stream - build streams
  • 48. Build streams from arrays Integer[] integers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Stream<Integer> stream = Stream.of(integers); Add text here... Stream - build streams
  • 49. Intermediate operations (return Stream) ❖ filter() ❖ map() ❖ sorted() ❖ …. Add text here... Stream - Operations
  • 50. // get even numbers Stream<Integer> evenNumbers = stream .filter(i -> i%2 == 0); // Now evenNumbers have {2, 4, 6, 8} Add text here... Stream - filter()
  • 51. Terminal operations ❖ forEach() ❖ collect() ❖ match() ❖ …. Add text here... Stream - Operations
  • 52. // get even numbers evenNumbers.forEach(i -> System.out.println(i)); /* Console output * 2 * 4 * 6 * 8 */ Add text here... Stream - forEach()
  • 53. Converting stream to list List<Integer> numbers = evenNumbers.collect(Collectors.toList()); Converting stream to array Integer[] numbers = evenNumbers.toArray(Integer[]::new); Add text here... Stream - Converting to collections
  • 55. What’s new in Date/Time? Add text here... Date / Time
  • 56. ● Why do we need a new Date/Time API? Add text here... Date / Time ○ Objects are not immutable ○ Naming ○ Months are zero-based
  • 57. ● LocalDate Add text here... Date / Time ○ A LocalDate is a date, with a year, month, and day of the month LocalDate today = LocalDate.now(); LocalDate christmas2015 = LocalDate.of(2015, 12, 25); LocalDate christmas2015 = LocalDate.of(2015, Month.DECEMBER, 25);
  • 58. Java 7: Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); Date dt = c.getTime(); Java 8: LocalDate tomorrow = LocalDate.now().plusDay(1); Add text here... Date / Time
  • 59. ● Temporal adjuster Add text here... Date / Time LocalDate nextPayDay = LocalDate.now() .with(TemporalAdjusters.lastDayOfMonth());
  • 60. ● Create your own adjuster TemporalAdjuster NEXT_WORKDAY = w -> { LocalDate result = (LocalDate) w; do { result = result.plusDays(1); } while (result.getDayOfWeek().getValue() >= 6); return result; }; LocalDate backToWork = today.with(NEXT_WORKDAY); Add text here... Date / Time
  • 61. For further questions, send to us: hcmc-vision@axonactive.vn
  • 62. Add text here... References ❖ Java Platform Standard Edition 8 Documentation, (http://docs.oracle.com/javase/8/docs/) ❖ Java 8 In Action, Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft. ❖ Beginning Java 8 Language Features, Kishori Sharan. ❖ What’s new in Java 8 - Pluralsight

Notas del editor

  1. The code is quite not elegant and not easy to read. Anonymous classes use a bulky syntax. Lambda expressions use a very concise syntax to achieve the same result.
  2. The body of a lambda expression is a block of code enclosed in braces. Like a method's body, the body of a lambda expression may declare local variables; use statements including break, continue, and return; throw exceptions, etc.
  3. A lambda expression does not have a name. A lambda expression does not have a throws clause. It is inferred from the context of its use and its body. A lambda expression cannot declare type parameters. That is, a lambda expression cannot be generic A lambda expression does not have a explicit return type. It is auto recognized by the compiler from the context of its use and from its body.
  4. Accessing outer scope variables from lambda expressions is very similar to anonymous objects. You can access final variables from the local outer scope as well as instance fields and static variables
  5. So where exactly can you use lambdas? You can use a lambda expression in the context of a functional interface. Don’t worry if this sounds abstract; we now explain in detail what this means and what a functional interface is.
  6. Functional Interface is a new term of Java 8 The functional interface is an normal interface with only one abstract method. Take a look at the example here, the well-known Runnable and Comparator interface are now become functional interface, so what we can see here that the term of functional interface is new but all the interfaces back from previous Java versions are becoming functional interface without any needed of modification.
  7. When we count the abstract method from an interface to check if it’s functional interface or not. The methods from Object class don’t count. Why some methods of the Object class sometimes are added to an interface? But most of the time and this is the reason because someone would like to redeclared methods from Object class in the interface in order to extend comments from Object’s class in order to give some special semantic and to add javadoc that might be different from Object class. http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Comparator.java/?v=source
  8. By the default, the compiler of Java will automatically check if interface is a functional interface or not. But for convenience, the functional interface can be annotated inside the code.
  9. It can be annotated by adding @FunctionalInterface on the top of the interface like the example below. By doing so, the IDE will help you to detect if it is a functional interface before compiler do its job.
  10. In this example, I declared another abstract method in the functional interface and as you can see, with the annotation, the IDE will check and show an error message that this interface is not a functional interface. So you can immediately notice and correct the problem.
  11. With the new term of functional interface defined in java 8. It also includes a brand new sets of functional interfaces.
  12. All these functional interfaces are defined in new package named java.util.function. It contains around 43 interfaces and grouped into 4 categories as I listed below: Supplier, consumer, predicate, function. You will see and use it a lot when you working with Java 8 and lambda expression. In the scope of this presentation I will not go and explain for every interfaces. Instead, I will pick one of them to give you an example.
  13. Classes implement interface that contains a default method, they can perform following: - Not override the default method and will inherit the default method - Override the default method similar to other methods we override in subclass - Redeclare default method as abstract, which force subclass to override it
  14. Classes implement interface that contains a default method, they can perform following: - Not override the default method and will inherit the default method - Override the default method similar to other methods we override in subclass - Redeclare default method as abstract, which force subclass to override it
  15. Let’s talk about why the stream is efficient. Nowaday, most of computer are using multiple CPUs, so we will take advantages of that to the stream in order to process data parallelly.
  16. Let’s talk about why the stream is efficient. Nowaday, most of computer are using multiple CPUs, so we will take advantages of that to the stream in order to process data parallelly.
  17. Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
  18. Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
  19. Terminal operations return a result of a certain type instead of again a Stream.
  20. Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
  21. Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
  22. statefull Date is not a date, but a timestamp, Calendar is mix of dates and times… have to work with Joda API. But there still have problem with the performance… this new API is base on Joda and was implemented by joda team