Post on 10-May-2015
description
transcript
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
Java 7Collections.sort(people, new Comparator<Person>() { public int compare(Person x, Person y) { return x.getName().compareTo(y.getName()); } });
5
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
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())); !!!
int compare(Person x, Person y)
18
Comparatorsimport static java.util.Comparator.comparing; … !sort(people, comparing((Person p) -> p.getName());
22
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
Exercise!git clone https://github.com/fredriv/fp-java8
open Exercise_1_Lambda_Expressions_Test.java in your favourite editor
mvn test
40
What’s wrong with using List::sort ?Modifies existing collection
Others may be using it?
Concurrency issues
Performance
42
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)));
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
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
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
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