KEMBAR78
Java8 and Functional Programming | PPTX
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!

Java8 and Functional Programming

  • 1.
  • 2.
    What has beenhappening 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 “Incomputer 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 LambdaExpression ❖ 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 //Anonymousversion 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 inJava8 ❖ 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 ❖ functionalinterface specifies exactly one abstract method ❖ Examples: ❖ Predicate<T>:boolean test(T t) ❖ Comparator<T>:compare(T o1, T o2)
  • 11.
  • 12.
    Default Methods ❖ Interfacecan contain method signatures for which an implementation class doesn’t have to provide implementation ❖ interface can now provide default method implementation
  • 13.
    Streams ❖ Manipulate collectionof 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 problemwith Null ❖ source of error: NPE ❖ bloats code ❖ meaningless ❖ break java philosophy ❖ a hole in type system
  • 18.
    –Tony Hoare Introducing Nullreference in ALGOL W in 1965 was “my billion-dollar mistake”
  • 19.
    Optionals ❖ Groovy safenavigation operator+Elvis operator ❖ String version = computer?.soundcard?.uSB.version ?: "UNKNOWN";
  • 20.
    Optionals ❖ how tomodel “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!