+ All Categories
Home > Software > Functional programming in Java 8 - workshop at flatMap Oslo 2014

Functional programming in Java 8 - workshop at flatMap Oslo 2014

Date post: 10-May-2015
Category:
Upload: fredrik-vraalsen
View: 452 times
Download: 2 times
Share this document with a friend
Description:
Slides from a workshop on Functional programming in Java 8, held at the flatMap Oslo conference 2014.
Popular Tags:
70
Functional Programming in Java 8 flatMap 2014 Fredrik Vraalsen – @fredriv 1
Transcript

Functional Programming in Java 8!

flatMap 2014 !!

Fredrik Vraalsen – @fredriv

1

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 function9

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

10

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

11

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

BodyReturn type?

Parameter list

(Person x, Person y) -> {

12

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

Parameter list

BodyReturn type?

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

};return

13

LambdaComparator<Person> byName =

Parameter list

BodyReturn type?

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

14

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

15

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

16

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

17

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

int compare(Person x, Person y)

18

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

(Person, Person) -> int

19

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

(Dog, Dog) -> int

20

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

21

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

22

Cool! !

!

!

!

Now onwards...© Fredrik Vraalsen 2013

Method handlesReference to methods

Can be used in place of lambdas

24

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

25

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

(Person) -> String

26

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

(Person) -> String

27

Ok, nice... What else?

© Fredrik Vraalsen 2012

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

29

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

30

Extension methods

Defender Method Default Method

(Virtual) Extension Method31

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 Method32

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

Defender Method Default Method

(Virtual) Extension Method33

Java 8 extension methodsExtend interfaces with new methods

Compatibility

Default implementation

Override

Requires modification of original interface34

C# extension methods“Add” methods to existing types

Without modifying original type

Defined as static methods

Called as instance methods

35

Scala Traits“Interfaces on steroids”

Method implementations

Variables

Everything a class can have – except constructors

Can mix in multiple traits36

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

Without modifying original type

Implicit wrapper object

37

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

38

So far, so good?Lambdas

Method handles

Extension methods

39

Exercise!git clone https://github.com/fredriv/fp-java8

open Exercise_1_Lambda_Expressions_Test.java in your favourite editor

mvn test

40

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

42

Streams

© Fredrik Vraalsen 2008

The old fashioned way

44

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

45

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

Streams – pipelines

46

!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)

47

Examples

48

Java 7: !Map<String, List<Article>> relatedArticles = new HashMap<>();!for (ArticleTransport transport : articleTransports) { Article article = convertToArticle(transport); String category = getCategory(article);! List<Article> articles = relatedArticles.get(category); if (articles == null) { articles = new ArrayList<>(); relatedArticles.put(category, articles); } articles.add(article);}

Examples

49

Java 8: !Map<String, List<Article>> relatedArticles = articleTransports.stream() .map(transport -> convertToArticle(transport)) .collect(Collectors.groupingBy(article -> getCategory(article)));

Examples

50

Java 7: !for (Map.Entry<K, List<Article>> e : relatedArticles.entrySet()) { result.put(e.getKey(), convertToTeasers(e.getValue()));}

Examples

51

Java 7: !for (Map.Entry<K, List<Article>> e : relatedArticles.entrySet()) { result.put(e.getKey(), convertToTeasers(e.getValue()));}!!Java 8: !relatedArticles.forEach((k, v) -> result.put(k, convertToTeasers(v)));

Performance

© Fredrik Vraalsen 2012

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

53

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

54

Streamsjava.util.stream

Create new results

Lazy

Parallelizable

55

More cool stuff in Java 8String join

Collection removeIf (≈ filter)

Map getOrDefault, putIfAbsent, replace, forEach, etc.

java.util.Optional

java.util.stream.Collectors

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

java.nio.file.Files lines56

Exercise!Exercise_2_Streams_Test.java

57

What’s missing?© Fredrik Vraalsen 2012

What’s missing?Immutability

Value types

Data structures (lists, maps, etc.)

Concurrency

59

What’s the big deal?Functional programming is all about values!

And transformations (functions) computing new values

Parallellism vs. Concurrency

Robustness

Testability

60

Some help to be foundImmutable collections

Google Guava, FunctionalJava, clj-ds

Concurrency mechanisms

Akka (Actors, STM)

61

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

62

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

63

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

64

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 66

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!

Important things are still missing

67

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

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

68

Questions?

© Fredrik Vraalsen 2012

[email protected] / @fredriv


Recommended