SlideShare a Scribd company logo
Java8
Yiguang Hu
What has been happening in
Computer
❖ Moor’s Law no longer applicable
❖ Computer speed is not increasing unlimited
❖ MultiCore Computer
❖ Pre-Java8 does not take advantage of multicore
computer Power
❖ Threading is hard, multicore make it harder
Computer Languages
❖ Groovy, Scala, Clojure, Kotlin, JavaScript/CoffeeScript,
Go, Swift, Lua, ErLang, Haskell, Ruby,C#,F#,…
❖ Closure
❖ Lambda Expression
❖ Pre-Java8 Did not have this, so what?
What is Closure
“In computer science, a closure is a first-class function with
free variables that are bound in the lexical environment.”
Groovy Closure
def myConst = 5
def incByConst = { num -> num + myConst }
println incByConst(10) //==>15
myConst = 20
println incByConst(10) //==>30
def result=[]
(1..10).collect(result,{a->a*a})
result==[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
What is Lambda Expression
❖ A concise representation of an anonymous
function that can be passed around:
❖ doesn't have a name, but has
❖ a list of parameters
❖ a body
❖ a return type
❖ possibly a list of exceptions
Example Lambda Expression
//Anonymous version
Runnable r1 = new Runnable(){
@Override
public void run(){
System.out.println("Hello world one!");
}
};
// Lambda Runnable
Runnable r2 = () -> System.out.println("Hello world two!");
// Run em!
r1.run();
r2.run();
Compare the one-liner lambda with the 4+ lines legacy code!
What’s new in Java8
❖ Lambda expression
❖ Default methods
❖ Stream
❖ optionals
❖ Date/Time API
What Lambda Expression
brings?
❖ Pass code concisely-functions are passed as values
❖ Collection:
❖ List<Person> pl ;//Given a list of Persons
❖ looping: pl.forEach( p -> p.printName() );
❖ filtering and chaining:
❖ pl.stream().filter(p->p.getAge()>30).sort(comparing((a)-
>a.getAge())).forEach(Person::printName);
❖ This one line replaces 20 lines of traditional code and does more
(later on stream)
functional interfaces
❖ functional interface specifies exactly one abstract
method
❖ Examples:
❖ Predicate<T>:boolean test(T t)
❖ Comparator<T>:compare(T o1, T o2)
Default Methods
❖ pl.stream().filter(p-
>p.getAge()>30).sort(comparing((a)-
>a.getAge()).reversed().thenComparing(Person::
getHeight())).forEach(Person::printName);
Default Methods
❖ Interface can contain method signatures for which an
implementation class doesn’t have to provide
implementation
❖ interface can now provide default method
implementation
Streams
❖ Manipulate collection of data in a declarative way.
❖ Streams can be processed in parallel transparently
without having to write any multithreaded code!
Stream example
❖ pl.stream().filter(p->p.getAge()>30).sort(comparing((a)-
>a.getAge()).reversed().thenComparing(Person::getHeigh
t())).map(Person::getName()).collect(toList))
❖ To Exploit multicore architecture and execute the code in
parallel
❖ pl.parallelStream().filter(p-
>p.getAge()>30).sort(comparing((a)-
>a.getAge()).reversed().thenComparing(Person::getHeigh
t())).map(Person::getName()).collect(toList))
Hi Map Collect/Reduce
❖ pl.parallelStream().filter(p-
>p.getAge()>30).sort(comparing((a)-
>a.getAge()).reversed().thenComparing(Person::getHei
ght())).map(Person::getName()).collect(toList))
❖ pl.parallelStream().filter(p-
>p.getAge()>30).sort(comparing((a)-
>a.getAge()).reversed().thenComparing(Person::getHei
ght())).map(Person::getSallary()).reduce(Integer::sum)).get
()
Optionals
❖ String version =
computer.getSoundcard().getUSB().getVersion();
❖ Problem: Multiple NPE possible. Traditional way:
String version = "UNKNOWN";
if(computer != null){
Soundcard soundcard = computer.getSoundcard();
if(soundcard != null){
USB usb = soundcard.getUSB();
if(usb != null){
version = usb.getVersion();
}
}
}
Optionals
❖ The problem with Null
❖ source of error: NPE
❖ bloats code
❖ meaningless
❖ break java philosophy
❖ a hole in type system
–Tony Hoare
Introducing Null reference in ALGOL W in 1965 was
“my billion-dollar mistake”
Optionals
❖ Groovy safe navigation operator+Elvis operator
❖ String version = computer?.soundcard?.uSB.version ?:
"UNKNOWN";
Optionals
❖ how to model “absence of a value”
❖ Scala introduced Option[T]
❖ Java 8 call it Optional[T]
❖ Optional<String> version =
optcomputer.map(Computer::getSoundcard).map(Sound
Card::getUSB).map(USB::getVersion)
Beyond Java 8
❖ Functional programming: Focus on What
❖ Scala example
❖ flatten(List(List(1, 1), 2, List(3, List(5, 8))))
❖ result: List(1, 1, 2, 3, 5, 8)
❖ Imperative programming: Focus on How
❖ Many lines needed to do the above 1-line job
❖ Functional programming is itself a great topic!

More Related Content

What's hot (20)

PDF
Clojure+ClojureScript Webapps
Falko Riemenschneider
 
PPTX
Briefly Rust
Daniele Esposti
 
PDF
Cap'n Proto (C++ Developer Meetup Iasi)
Ovidiu Farauanu
 
PDF
Functions - complex first class citizen
Vytautas Butkus
 
PDF
What make Swift Awesome
Sokna Ly
 
PDF
Clojure for Rubyists
Jean-François Héon
 
PPTX
Next Generation Language Go
Yoichiro Shimizu
 
PDF
Meetup C++ A brief overview of c++17
Daniel Eriksson
 
PDF
Dynamic Swift
Saul Mora
 
PPTX
Ruby basics ||
datt30
 
PDF
Linguistic Symbiosis between Actors and Threads
ESUG
 
PDF
Python intro
Abhinav Upadhyay
 
PPTX
Just Kotlin
Ismail Habib Muhammad
 
PDF
Kotlin workshop 2018-06-11
Åsa Pehrsson
 
PPTX
Object Oriented Programming - Inheritance
Dudy Ali
 
PPT
Oop lecture5
Shahriar Robbani
 
PPT
Templates
Nilesh Dalvi
 
PPTX
Coding convention
Khoa Nguyen
 
PPTX
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
PDF
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
LogeekNightUkraine
 
Clojure+ClojureScript Webapps
Falko Riemenschneider
 
Briefly Rust
Daniele Esposti
 
Cap'n Proto (C++ Developer Meetup Iasi)
Ovidiu Farauanu
 
Functions - complex first class citizen
Vytautas Butkus
 
What make Swift Awesome
Sokna Ly
 
Clojure for Rubyists
Jean-François Héon
 
Next Generation Language Go
Yoichiro Shimizu
 
Meetup C++ A brief overview of c++17
Daniel Eriksson
 
Dynamic Swift
Saul Mora
 
Ruby basics ||
datt30
 
Linguistic Symbiosis between Actors and Threads
ESUG
 
Python intro
Abhinav Upadhyay
 
Kotlin workshop 2018-06-11
Åsa Pehrsson
 
Object Oriented Programming - Inheritance
Dudy Ali
 
Oop lecture5
Shahriar Robbani
 
Templates
Nilesh Dalvi
 
Coding convention
Khoa Nguyen
 
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
LogeekNightUkraine
 

Similar to Java8 and Functional Programming (20)

PPT
Concurrency in go
borderj
 
PPT
Go lang introduction
yangwm
 
PDF
Loom and concurrency latest
Srinivasan Raghavan
 
PDF
10 reasons to be excited about go
Dvir Volk
 
PDF
Introduction to clojure
Abbas Raza
 
ODP
Introduction to Go for Java Developers
Laszlo Csontos
 
PDF
Google Interview Questions By Scholarhat
Scholarhat
 
PDF
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
PPTX
C++ theory
Shyam Khant
 
PDF
Measuring maintainability; software metrics explained
Dennis de Greef
 
PDF
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Raffi Khatchadourian
 
PPTX
Go Programming language, golang
Basil N G
 
PDF
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
PPTX
Java 8
Sudipta K Paik
 
PDF
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
PDF
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
PPTX
Async fun
💡 Tomasz Kogut
 
PDF
Beyond PITS, Functional Principles for Software Architecture
Jayaram Sankaranarayanan
 
PDF
Compiler Construction | Lecture 10 | Data-Flow Analysis
Eelco Visser
 
PDF
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Concurrency in go
borderj
 
Go lang introduction
yangwm
 
Loom and concurrency latest
Srinivasan Raghavan
 
10 reasons to be excited about go
Dvir Volk
 
Introduction to clojure
Abbas Raza
 
Introduction to Go for Java Developers
Laszlo Csontos
 
Google Interview Questions By Scholarhat
Scholarhat
 
Functional Programming 101 for Java 7 Developers
Jayaram Sankaranarayanan
 
C++ theory
Shyam Khant
 
Measuring maintainability; software metrics explained
Dennis de Greef
 
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Raffi Khatchadourian
 
Go Programming language, golang
Basil N G
 
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Productive Programming in Java 8 - with Lambdas and Streams
Ganesh Samarthyam
 
Beyond PITS, Functional Principles for Software Architecture
Jayaram Sankaranarayanan
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Eelco Visser
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Ad

More from Yiguang Hu (10)

PPTX
Data analysis scala_spark
Yiguang Hu
 
PPTX
Introduction to Vert.x
Yiguang Hu
 
PPTX
Cross platform Mobile development on Titanium
Yiguang Hu
 
PPTX
Phone Gap
Yiguang Hu
 
PPT
Google Web Toolkits
Yiguang Hu
 
PPT
Clojure
Yiguang Hu
 
PDF
Why Grails
Yiguang Hu
 
PDF
Why Grails?
Yiguang Hu
 
PPT
Gsword
Yiguang Hu
 
PPT
Google Web Toolkits
Yiguang Hu
 
Data analysis scala_spark
Yiguang Hu
 
Introduction to Vert.x
Yiguang Hu
 
Cross platform Mobile development on Titanium
Yiguang Hu
 
Phone Gap
Yiguang Hu
 
Google Web Toolkits
Yiguang Hu
 
Clojure
Yiguang Hu
 
Why Grails
Yiguang Hu
 
Why Grails?
Yiguang Hu
 
Gsword
Yiguang Hu
 
Google Web Toolkits
Yiguang Hu
 
Ad

Recently uploaded (20)

PPTX
Student_Support_Services_Presentation.pptx
Muhammad439928
 
PDF
NotificationForTheTeachingPositionsAdvt012025.pdf
sunitsaathi
 
PDF
Sarkari Job Alerts in Marathi & English – Majhi Naukri
Reeshna Prajeesh
 
PDF
From-Idea-to-Business-Plan-A-Practical-Guide.pdf
eman youssif
 
PDF
Formwalaa: Your One-Stop Hub for Exam & Job Application Forms
Reeshna Prajeesh
 
PPTX
5G Model Site PPT WBA179_ROB_Ghorai (1).pptx
kousikmaity15
 
PPTX
Using the translanguaging to enhance RES
ssuserb7fdac
 
PDF
hr generalist training.pdf..............
a25075044
 
PPTX
Ganesh Mahajan Digital marketing Portfolio.pptx
ganeshmahajan786
 
PDF
corporate training firms in pune.........
a25075044
 
DOCX
PMCF (Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
PPTX
文凭复刻澳洲电子毕业证阳光海岸大学成绩单USC录取通知书
Taqyea
 
PPTX
原版英国牛津大学毕业证(Oxon毕业证书)如何办理
Taqyea
 
PDF
Find the Latest Government Jobs in One Click – Stay Updated with Daily Notifi...
Reeshna Prajeesh
 
PPT
SQL.pptkarim pfe rabatkarim pfe rabatkarim pfe rabat
Keeyvikyv
 
PDF
hr generalist certification.pdf.........
a25075044
 
PDF
Walking &Working Surfaces – Stairs & Ladders.pdf
دكتور تامر عبدالله شراكى
 
PDF
Web Developer Jobs in Jaipur Your Gateway to a Thriving Tech Career in Rajast...
vinay salarite
 
PDF
165. Reviewer Certificate in Physical Science
Manu Mitra
 
PDF
The Rising Prominence of Podcasts Today
Raj Kumble
 
Student_Support_Services_Presentation.pptx
Muhammad439928
 
NotificationForTheTeachingPositionsAdvt012025.pdf
sunitsaathi
 
Sarkari Job Alerts in Marathi & English – Majhi Naukri
Reeshna Prajeesh
 
From-Idea-to-Business-Plan-A-Practical-Guide.pdf
eman youssif
 
Formwalaa: Your One-Stop Hub for Exam & Job Application Forms
Reeshna Prajeesh
 
5G Model Site PPT WBA179_ROB_Ghorai (1).pptx
kousikmaity15
 
Using the translanguaging to enhance RES
ssuserb7fdac
 
hr generalist training.pdf..............
a25075044
 
Ganesh Mahajan Digital marketing Portfolio.pptx
ganeshmahajan786
 
corporate training firms in pune.........
a25075044
 
PMCF (Performance Monitoring and Coaching Form
ROSALIESOMBILON
 
文凭复刻澳洲电子毕业证阳光海岸大学成绩单USC录取通知书
Taqyea
 
原版英国牛津大学毕业证(Oxon毕业证书)如何办理
Taqyea
 
Find the Latest Government Jobs in One Click – Stay Updated with Daily Notifi...
Reeshna Prajeesh
 
SQL.pptkarim pfe rabatkarim pfe rabatkarim pfe rabat
Keeyvikyv
 
hr generalist certification.pdf.........
a25075044
 
Walking &Working Surfaces – Stairs & Ladders.pdf
دكتور تامر عبدالله شراكى
 
Web Developer Jobs in Jaipur Your Gateway to a Thriving Tech Career in Rajast...
vinay salarite
 
165. Reviewer Certificate in Physical Science
Manu Mitra
 
The Rising Prominence of Podcasts Today
Raj Kumble
 

Java8 and Functional Programming

  • 2. What has been happening in Computer ❖ Moor’s Law no longer applicable ❖ Computer speed is not increasing unlimited ❖ MultiCore Computer ❖ Pre-Java8 does not take advantage of multicore computer Power ❖ Threading is hard, multicore make it harder
  • 3. Computer Languages ❖ Groovy, Scala, Clojure, Kotlin, JavaScript/CoffeeScript, Go, Swift, Lua, ErLang, Haskell, Ruby,C#,F#,… ❖ Closure ❖ Lambda Expression ❖ Pre-Java8 Did not have this, so what?
  • 4. What is Closure “In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.”
  • 5. Groovy Closure def myConst = 5 def incByConst = { num -> num + myConst } println incByConst(10) //==>15 myConst = 20 println incByConst(10) //==>30 def result=[] (1..10).collect(result,{a->a*a}) result==[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • 6. What is Lambda Expression ❖ A concise representation of an anonymous function that can be passed around: ❖ doesn't have a name, but has ❖ a list of parameters ❖ a body ❖ a return type ❖ possibly a list of exceptions
  • 7. Example Lambda Expression //Anonymous version Runnable r1 = new Runnable(){ @Override public void run(){ System.out.println("Hello world one!"); } }; // Lambda Runnable Runnable r2 = () -> System.out.println("Hello world two!"); // Run em! r1.run(); r2.run(); Compare the one-liner lambda with the 4+ lines legacy code!
  • 8. What’s new in Java8 ❖ Lambda expression ❖ Default methods ❖ Stream ❖ optionals ❖ Date/Time API
  • 9. What Lambda Expression brings? ❖ Pass code concisely-functions are passed as values ❖ Collection: ❖ List<Person> pl ;//Given a list of Persons ❖ looping: pl.forEach( p -> p.printName() ); ❖ filtering and chaining: ❖ pl.stream().filter(p->p.getAge()>30).sort(comparing((a)- >a.getAge())).forEach(Person::printName); ❖ This one line replaces 20 lines of traditional code and does more (later on stream)
  • 10. functional interfaces ❖ functional interface specifies exactly one abstract method ❖ Examples: ❖ Predicate<T>:boolean test(T t) ❖ Comparator<T>:compare(T o1, T o2)
  • 12. Default Methods ❖ Interface can contain method signatures for which an implementation class doesn’t have to provide implementation ❖ interface can now provide default method implementation
  • 13. Streams ❖ Manipulate collection of data in a declarative way. ❖ Streams can be processed in parallel transparently without having to write any multithreaded code!
  • 14. Stream example ❖ pl.stream().filter(p->p.getAge()>30).sort(comparing((a)- >a.getAge()).reversed().thenComparing(Person::getHeigh t())).map(Person::getName()).collect(toList)) ❖ To Exploit multicore architecture and execute the code in parallel ❖ pl.parallelStream().filter(p- >p.getAge()>30).sort(comparing((a)- >a.getAge()).reversed().thenComparing(Person::getHeigh t())).map(Person::getName()).collect(toList))
  • 15. Hi Map Collect/Reduce ❖ pl.parallelStream().filter(p- >p.getAge()>30).sort(comparing((a)- >a.getAge()).reversed().thenComparing(Person::getHei ght())).map(Person::getName()).collect(toList)) ❖ pl.parallelStream().filter(p- >p.getAge()>30).sort(comparing((a)- >a.getAge()).reversed().thenComparing(Person::getHei ght())).map(Person::getSallary()).reduce(Integer::sum)).get ()
  • 16. Optionals ❖ String version = computer.getSoundcard().getUSB().getVersion(); ❖ Problem: Multiple NPE possible. Traditional way: String version = "UNKNOWN"; if(computer != null){ Soundcard soundcard = computer.getSoundcard(); if(soundcard != null){ USB usb = soundcard.getUSB(); if(usb != null){ version = usb.getVersion(); } } }
  • 17. Optionals ❖ The problem with Null ❖ source of error: NPE ❖ bloats code ❖ meaningless ❖ break java philosophy ❖ a hole in type system
  • 18. –Tony Hoare Introducing Null reference in ALGOL W in 1965 was “my billion-dollar mistake”
  • 19. Optionals ❖ Groovy safe navigation operator+Elvis operator ❖ String version = computer?.soundcard?.uSB.version ?: "UNKNOWN";
  • 20. Optionals ❖ how to model “absence of a value” ❖ Scala introduced Option[T] ❖ Java 8 call it Optional[T] ❖ Optional<String> version = optcomputer.map(Computer::getSoundcard).map(Sound Card::getUSB).map(USB::getVersion)
  • 21. Beyond Java 8 ❖ Functional programming: Focus on What ❖ Scala example ❖ flatten(List(List(1, 1), 2, List(3, List(5, 8)))) ❖ result: List(1, 1, 2, 3, 5, 8) ❖ Imperative programming: Focus on How ❖ Many lines needed to do the above 1-line job ❖ Functional programming is itself a great topic!