Java8 and Functional Programming

21
Java8 Yiguang Hu

Transcript of Java8 and Functional Programming

Page 1: Java8 and Functional Programming

Java8Yiguang Hu

Page 2: Java8 and Functional Programming

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

Page 3: Java8 and Functional Programming

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?

Page 4: Java8 and Functional Programming

What is Closure

“In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.”

Page 5: Java8 and Functional Programming

Groovy Closuredef 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]

Page 6: Java8 and Functional Programming

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

Page 7: Java8 and Functional Programming

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!

Page 8: Java8 and Functional Programming

What’s new in Java8

❖ Lambda expression❖ Default methods❖ Stream❖ optionals❖ Date/Time API

Page 9: Java8 and Functional Programming

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)

Page 10: Java8 and Functional Programming

functional interfaces

❖ functional interface specifies exactly one abstract method❖ Examples:❖ Predicate<T>:boolean test(T t)❖ Comparator<T>:compare(T o1, T o2)

Page 11: Java8 and Functional Programming

Default Methods

❖ pl.stream().filter(p->p.getAge()>30).sort(comparing((a)->a.getAge()).reversed().thenComparing(Person::getHeight())).forEach(Person::printName);

Page 12: Java8 and Functional Programming

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

Page 13: Java8 and Functional Programming

Streams

❖ Manipulate collection of data in a declarative way.

❖ Streams can be processed in parallel transparently without having to write any multithreaded code!

Page 14: Java8 and Functional Programming

Stream example

❖ pl.stream().filter(p->p.getAge()>30).sort(comparing((a)->a.getAge()).reversed().thenComparing(Person::getHeight())).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::getHeight())).map(Person::getName()).collect(toList))

Page 15: Java8 and Functional Programming

Hi Map Collect/Reduce❖ pl.parallelStream().filter(p->p.getAge()>30).sort(comparing((a)->a.getAge()).reversed().thenComparing(Person::getHeight())).map(Person::getName()).collect(toList))

❖ pl.parallelStream().filter(p->p.getAge()>30).sort(comparing((a)->a.getAge()).reversed().thenComparing(Person::getHeight())).map(Person::getSallary()).reduce(Integer::sum)).get()

Page 16: Java8 and Functional Programming

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(); } }}

Page 17: Java8 and Functional Programming

Optionals

❖ The problem with Null❖ source of error: NPE❖ bloats code❖ meaningless❖ break java philosophy❖ a hole in type system

Page 18: Java8 and Functional Programming

–Tony Hoare

Introducing Null reference in ALGOL W in 1965 was“my billion-dollar mistake”

Page 19: Java8 and Functional Programming

Optionals

❖ Groovy safe navigation operator+Elvis operator❖ String version =

computer?.soundcard?.uSB.version ?: "UNKNOWN";

Page 20: Java8 and Functional Programming

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(SoundCard::getUSB).map(USB::getVersion)

Page 21: Java8 and Functional Programming

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!