Professional Documents
Culture Documents
Lambda in Java8aaa
Lambda in Java8aaa
Java 8
Issue is planned for summer of 2013 Java 8 will contain the most significant changes and innovation in Java
lambda (closures) Interface evolution (default methods) Evolution of Collections library (bulk operations) Simplified syntax of parallel computation with libraries
How to try it
OpenJDK 8
Times change
1995 (when Java was born)
No support of lambda in most popular languages
Today:
++ has lambda C# has lambda Any new language has lambda
Lambda-calculus
Mathematical definition of mapping (function)
square : REAL REAL "+": [REAL REAL] REAL
Thread t = new Thread (new Runnable() { void run () { System.out.println("hello"); } }); t.start();
What is lambda-expression
Lambda-expression is anonymous method with arguments and body Example
(Object o) -> o.toString() s -> s.length()
Short syntax:
button.addActionListener(e -> System.out.println(e.getWhen()));
Code as data
Code (behavior) may be passed as an argument
List<String> list = new ArrayList<String>(); list.add("first"); list.add("second"); list.add("third"); list.forEach((String s)->{System.out.println(s);});
External iteration
for (Shape s: shapes) { if (s.getColor() == RED) s.setColor(BLUE); } Client control iteration - external iteration Sequential iteration In this code - what and how
When client controls iteration
Internal iteration
shapes.forEach(s->{ if (s.getColor() == RED) s.setColor(BLUE); }); Iteration controlled by library More what, less how Library can use
parallelism custom order of iterating lazy calculation
When iteration is controlled by iterator
Interface evolution
Interface Collection has new method forEach interface Collection<T> { forEach(Block<T> action) default { for (T t: this) { Default method new feature of action.apply(t); language. } Virtual method can have default implementation. } This allows to transfer control } over iteration to library. Block<T>, Predicate<T> - functional interface from Java 8
Multiple inheritance?
Dafault-methods allow to add behavior to interface (not state) Is this multiple inheritance?
Java has multiple type inheritance Java will have multiple behavior inheritance No multiple inheritance of state. Ever.
Collection, default-methods
With lambda Java Collection Framework became stale. It needed to change. Interface Collection has new methods:
forEach removeAll retailAll
interface Collection<T> { forEach(Block<T> action) default { for (T t: this) { action.apply(t); } }
boolean removeAll default ( Predicate <? Super T> filter) { boolean removed = false; Iterator<E> each = this.iterator(); while(each.hasNext()) { if(filter.test(each.next())) { each.remove(); removed = true; } } return removed;
Iterable
collection.filter(f->f.isBlue()) .map (f->g.getContainer()) .foreach(s->System.out.println(s))
It is possible to pass behavior to these methods because of functional interfaces Predicate<T>, Mapper <T,U>, Block<T> defined in Java 8
Predicate
public interface Predicate<T> { boolean test(T t);
Predicate<T> and(Predicate<? super T> p) default { return t -> this.test(t) && p.test(t); }
Predicate<T> negate() default { return t -> !this.test(t); } Predicate<T> or(Predicate<? super T> p) default { return t -> this.test(t) || p.test(t); } Predicate<T> xor(Predicate<? super T> p) default { return t -> this.test(t) ^ p.test(t); }
Mapper
public interface Mapper<T, U> { U map(T t); public <V> Mapper<T, V> compose( Mapper<? super U, ? extends V> after) default { return Mappers.chain(this, after); } }
Block
public interface Block<T> { void apply(T t); }
List<String> list = new ArrayList<String>(); // ... add elements to list List<String> listRes = new ArrayList<String>(); list.filter(pr1.or(pr2).negate()) .into(listRes);
Iterable (cont.)
filter map forEach into sorted aggregate (eg. max, sum ) groupBy mapReduce
Example
Select author, sum(pages) from documents group by author
Map<String, Integer> map = new HashMap(); for (Document d: document) { String author = d.getAuthor(); Integer sum = map.get(author); if (sum==null) sum=0; map.put(author, sum+d.getPageCount()); } Map <String, Integer> map = documents.aggregateBy(d->d.getAuthor(), ()->0, (sum, d) ->sum+d.getPageCount());
Method Reference ::
Method reference :: introduced both for static and instance methods Facility to convert from one interface to another
Task t = () -> System.out.println("hi"); Runnable r = t::invoke;
Equivalent
Runnable r1 = System.out::println; Runnable r2 = () -> { System.out.println(); }
Parallelism
Libraries can hide syntactic and semantic complexity of parallelism Code for sequential and parallel execution should be more similar in syntax
At this moment syntaxes are completely different Code for sequential execution looks very simple Code for parallel execution looks supercompex the complexity of code hides semantic of what we want to calculate
Example
int sumOfWeight = shapes .parallel() .filter(s->s.getColor()==BLUE) .map(s->getWeight()) .sum();
Lambda advantages
Lambda helps to develop more expressive API Delegate to library to control infrastructure flow
Analogy like inversion of control between client code and library
Sorting (Java-style)
Collections.sort(list, new Comparator() { public int compare(Person x, Person y) return x.getLastName().compareTo(y.getLastName()); })
Default-methods - Combinators
public interface Comparator<T> { int compare (T o1, T o2);
Comparator<T> reverse () default { Combining return (o1, o2)->compare (o2, o1); comparison } functions Comparator<T> compose (Comparator<T> other) default { return (o1, o2) -> { int cmp = compare (o1, o2); return cmp!=0?cmp:other.compare(o1, o2); }; } } Comparator<Person> byFirst = Comparator<Person> byLast = Comparator<Person> byFirstLast = byFirst.compose(byLast); Comparator<Person> byLastDesc = byLast.reverse();
people.sort(Comparators.comparing(p->p.getLastName())) people.sort(Comparators.comparing(p->p.getLastName()).reverse())
JVM translation
http://cr.openjdk.java.net/~briangoetz/lambda/la mbda-translation.html
Bibliography
http://tronicek.blogspot.com/2007/12/closur es-closure-is-form-of-anonymous_28.html Brian Goetz, The Road to Lambda, https://oracleus.activeevents.com/connect/se ssionDetail.ww?SESSION_ID=4862 http://www.jcp.org/en/jsr/summary?id=335 http://cr.openjdk.java.net/~briangoetz/lambd a/lambda-translation.html