Java 8 - Return of the Java

Post on 10-May-2015

694 views 2 download

Tags:

description

Introduction to new features in Java 8 and their use in functional programming, such as lambda methods, extension methods, method handles, the new Stream API, parallellism and laziness.

Transcript of Java 8 - Return of the Java

!1

RETURN OF THE AVAJ

JAVA EIGHT

Java 8 – what’s new?Lambdas, Extension Methods, SAMs, Streams, Method Handles, Oh My!

Nashorn JS engine

JSR-310: Date & time API

No more PermGen – where classloaders go to die

...!2

Java 8 – what’s new?Lambdas, Extension Methods, SAMs, Streams, Method Handles, Oh My!

Nashorn JS engine

JSR-310: Date & time API

No more PermGen – where classloaders go to die

...!3

Your Mission Should you choose to accept it

Sort a list of people by their names

Java 7Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } });

!5

We are not amused

© Fredrik Vraalsen 2012

Java 8Comparator<Person> byName = new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } };

Single Abstract Method !

(SAM)!7

Single Abstract MethodInterface with only one (non-default) method

Abstract class with only one abstract method

Sound familiar?

Pretty much every event listener, callback mechanism, ...

Can be replaced by a Lambda

!8

Lambda

Closure

Anonymous function!9

SAMComparator<Person> byName = new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } };

!10

SAMComparator<Person> byName = new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } };

BodyReturn type

Parameter list

Method name

Type

!11

LambdaComparator<Person> byName = new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } };

BodyReturn type

Parameter list

Method name

Type

!12

LambdaComparator<Person> byName = ! return x.getName().compareTo(y.getName()); };

BodyReturn type?

Parameter list

(Person x, Person y) -> {

!13

LambdaComparator<Person> byName = (Person x, Person y) ->

Parameter list

BodyReturn type?

x.getName().compareTo(y.getName());{

};return

!14

LambdaComparator<Person> byName =

Parameter list

BodyReturn type?

(x, y) -> x.getName().compareTo(y.getName()); (Person x, Person y)

!15

LambdaComparator<Person> byName = (x, y) -> x.getName().compareTo(y.getName()); !Collections.sort(people, byName);

!16

LambdaComparator<Person> byName = (x, y) -> x.getName().compareTo(y.getName()); !sort(people, byName);

!17

Lambda!!!sort(people, (x, y) -> x.getName().compareTo(y.getName()));

!18

Comparatorsimport static java.util.Comparator.comparing; … !sort(people, comparing((Person p) -> p.getName());

!19

Cool! !

!

!

!

Now onwards...© Fredrik Vraalsen 2013

Method handlesReference to methods

Can be used in place of lambdas

!21

Method handles!!!sort(people, comparing((Person p) -> p.getName()));

!22

Method handles!!!sort(people, comparing(Person::getName));

!23

Ok, nice... What else?

© Fredrik Vraalsen 2012

Extension methods!!!sort(people, comparing(Person::getName));

!25

Extension methods!!!people.sort(comparing(Person::getName));

!26

Extension methods

!27

java.util.List: ! default void sort(Comparator<? super E> c)

Extension methods

Defender Method Default Method

(Virtual) Extension Method!28

java.util.List: ! default void sort(Comparator<? super E> c)

Extension methodsjava.util.List: ! default void sort(Comparator<? super E> c) { } !

Defender Method Default Method

(Virtual) Extension Method!29

Extension methodsjava.util.List: ! default void sort(Comparator<? super E> c) { Collections.sort(this, c); } !

Defender Method Default Method

(Virtual) Extension Method!30

Java 8 extension methodsExtend interfaces with new methods

Compatibility

Default implementation

Override

Requires modification of original interface!31

C# extension methods“Add” methods to existing types

Without modifying original type

Defined as static methods

Called as instance methods

!32

Scala implicit classes“Add” methods or properties to existing types

Without modifying original type

Implicit wrapper object

!33

Java 7 vs 8Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } });

!vs

!people.sort(comparing(Person::getName));

!34

So far, so good?Lambdas

Method handles

Extension methods

!35

So, what’s the catch?© Fredrik Vraalsen 2012

What’s wrong with using List::sort ?Modifies existing collection

Others may be using it?

Concurrency issues

Performance

!37

Streams

© Fredrik Vraalsen 2008

The old fashioned way

!39

List<RoadData> filtered = new ArrayList<>();int count = 0; for (Iterator<RoadData> i = roadData.iterator(); i.hasNext() && count < 10; ) { RoadData data = i.next(); if (data.getName().contains(nameQuery)) { filtered.add(data); count++; } }

Streams

!40

!roadData.stream() .filter(r -> r.getName().contains(nameQuery)) .limit(10) .collect(Collectors.toList());

Streams – pipelines

!41

!roadData.stream() .filter(r -> r.getName().contains(nameQuery)) .limit(10) .collect(Collectors.toList());!!cat roadData.txt | grep … | head > output.txt

Streams – pipelinesSource

collection, array, generator function, IO channel, ...

Intermediate operations (Stream-producing)

filter, map, ...

Terminal operations (value-producing)

!42

Performance

© Fredrik Vraalsen 2012

Streams – performance!people.stream() .filter(p -> p.getAge() >= 18) .map(Person::getName) .collect(Collectors.toList());

!44

This one goes to 11!!people.parallelStream() .filter(p -> p.getAge() >= 18) .map(Person::getName) .collect(Collectors.toList());

!45

Scala FTW!!people.par .filter(_.age >= 18) .map(_.name)

!46

Streamsjava.util.stream

Create new results

Lazy

Parallelizable

!47

More cool stuff in Java 8String join

Collection removeIf (≈ filter)

List sort

Map getOrDefault, putIfAbsent, replace, forEach, etc.

java.util.stream.Collectors

count, sum, average, min, max, groupingBy, etc.

java.nio.file.Files lines!48

What’s missing?© Fredrik Vraalsen 2012

What’s missing?Immutability

Value types

Data structures (lists, maps, etc.)

Concurrency

!50

Some help to be foundImmutable collections

Google Guava, FunctionalJava, clj-ds

Concurrency mechanisms

Akka (Actors, STM)

!51

github.com/krukow/clj-dsPersistentVector<Person> people = Persistents.vector( new Person("Fredrik", 37), new Person("Hedda", 2));

!52

github.com/krukow/clj-dsPersistentVector<Person> people = Persistents.vector( new Person("Fredrik", 37), new Person("Hedda", 2));!PersistentVector<Person> morePeople = people.plus(new Person("Johannes", 4));

!53

github.com/krukow/clj-dsPersistentVector<Person> people = Persistents.vector( new Person("Fredrik", 37), new Person("Hedda", 2));!PersistentVector<Person> morePeople = people.plus(new Person("Johannes", 4));!morePeople.stream() .forEach(p -> System.out.println(p.getName()));

!54

Ready to make the jump!?

© Fredrik Vraalsen 2013

Play with it!Download – http://www.oracle.com/technetwork/java/

… or https://jdk8.java.net/download.html

Whitepapers – http://openjdk.java.net/projects/lambda/

FAQ – http://www.lambdafaq.org/

Supported in IntelliJ IDEA 12 & 13

Eclipse Java 8 beta plugin and NetBeans 8.0 RC !56

Why use X instead?Java 8 just released

Will be a long time before you can use it in enterprise dev!

Clojure and Scala available NOW! (JDK 1.6)

Important things are still missing

!57

Want to know more?^{Oslo "Socially Functional Programmers" #OsloSFP}

“Haskell på godt og vondt” – tonight 6pm @ Teknologihuset

http://www.meetup.com/Oslo-Socially-Functional/

Functional Programming in Java 8

http://2014.flatmap.no/

!58

Questions?

© Fredrik Vraalsen 2012

vraalsen@iterate.no / @fredriv