Dori Waldman

Lambda Expressions

CompletableFuture

Method References

Functional Interfaces

Default Methods

Streams

Optional Class

New Date/Time API
...
Agenda
Functional programming: “Lambda allow us to treat functionality as a method
argument (passing functions around)”
Syntax:
1) Infers syntax : return / type / {} / ()
Integer sub = (a, b) → a – b; // no need to write (int a, int b) -> { return a * b; }
Arrays.asList( "a", "b").forEach( e → System.out.println( e ) );
// no need to write ((String)e) → ...
Lambda (→)
Lambda (→)
2) Function as parameter
Lambda (→)
3) Eliminates the need of anonymous class
4) Make code more immutable
Lambda (→) , the bad parts
https://dzone.com/articles/whats-wrong-java-8-part-ii - be aware of auto-boxing
System.out.println((x -> x / 100 * (100 + 10)).apply(100)); // java does not know type of X
System.out.println((Integer x) -> x / 100 * 100 + 10).apply(100)); // → is a function , java does
not know Function type
System.out.println(((Function<Integer, Integer>) x -> x / 100 * 100 + 10).apply(100));
* Auto-boxing means automatic convert between primitive and object
To allow functions to take lambdas as arguments, Java 8 use “functional interface”
which is an interface with has only one abstract method (like Runnable)
Functional Interface
Interface (Default & Static method)
Default methods make interfaces similar to scala trait,
Interface must implement the default method each implement will inherit it
java.util.function contains 43 methods like:
BiFunction<T,U,R>
Represents a function that accepts two arguments and produces a result.
http://www.tutorialspoint.com/java8/java8_functional_interfaces.htm
Predicate<T> // represent a function that return true/false
public void calculate(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {
if(predicate.test(n)) { //test evaluate predicate on argument
System.out.println(n + " ");
}
}
}
calculate(list, n-> n%2 == 0 );
Function API
http://howtodoinjava.com/java-8/how-to-use-predicate-in-java-8/
Call methods by their names
allows us to reference constructors or methods without executing them
You can’t pass arguments to methods Reference
List names = ArrayList::new;
names.add(“a”);
names.add(“b”);
names.forEach(System.out::println);
Car carInstance = Car.create( Car::new );
Car::collide;
carInstance::drive;
Method reference (::)
Method reference vs Lamdba
Curring
function that returns a function instead of a result.
Java 8 brings new abilities to work with Collections,Arrays, or I/O resources as
input source
Stream API offers easy filtering, aggregation, and mapping actions
Operations can return stream (pipelined) or result (like collect())
parallelStream : leverage multicore architecture without the need to write any
specific code for it (using ForkJoinThreadPool)
http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/
https://dzone.com/articles/whats-wrong-java-8-part-iii
Stream
Stream() / filter() / map() return new stream object
Stream() convert collection to stream
Stream
collect() allows us to collect the results of a stream
Collectors are used to combine the stream result:
List<String>strings = Arrays.asList("a", "", "b", "");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
String mergedString = strings.stream().filter(string -> string.isEmpty()).collect(Collectors.joining(", "));
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
stats.getMax();
stats.getSum();
stats.getAverage();
Stream – Collectors & Aggregation
Stream – yet another example
Parallel Stream
CompletableFuture
Java 7 has no interface to get the async task result in the future , there is a way to get
the result outside of the future and when its done perform another action
Java 8 added Completefuture<T> interface
CompletableFuture
Optional is a container: it can hold a value of some type T or just be null.
It replace null checking and can avoid NullPointerException.
Integer value1 = null;
Integer value2 = new Integer(10);
Optional<Integer> a = Optional.ofNullable(value1); //represent null
Optional<Integer> b = Optional.of(value2);
Public Integer sum(Optional<Integer> a, Optional<Integer> b){
a.isPresent(); // false
Integer value1 = a.orElse(new Integer(5)); // 5
a.orElseGet( () -> 77 ) // instead of parameter it accept a method
Integer value2 = b.get(); // 10
return value1 + value2; // 15
}
What makes Optional truly appealing are methods such as ifPresent() and
orElseThrow() along with map() and filter() which all accept lambda
expressions ~ scala monad
Optional Class
java.util.Date & Calendar are not thread safe, developer need to manage timezone issues
popular solution JodaTime is 3#party not part of the Java api.
Java 8 has 2 implementation : Local / Zoned (which support timezone)
LocalDateTime currentTime = LocalDateTime.now(); //2014-12-10
LocalDate.now(Clock.systemUTC()) // Clock object provide access to datetime using timezone
// Clock can be used instead of System.currentTimeMillis() and TimeZone.getDefault().
LocalDate nextWeek = currentTime.plus(1, ChronoUnit.WEEKS); //2014-12-17
Period period = Period.between(currentTime, nextWeek);
Duration.between( currentTime, nextWeek ).toDays();
LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.TUESDAY)); //2014-12-16
LocalDate date = LocalDate.of(2014, Month.DECEMBER, 12);
ZonedDateTime date1 =
ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Karachi]");
DateTime (immutable)
DateTime
Concurrency
how-longadder-performs-better-than-atomiclong
Atomic are used to increment a variable across threads, faster than locks.
Java 8 added adders and accumulators which to improve Atomic
Concurrency
JVM options -XX:PermSize and –XX:MaxPermSize have been replaced by
-XX:MetaSpaceSize and -XX:MaxMetaspaceSize respectively
JVM
GC1
Built in base64 encoder/decoder
Invoke JAVA from JS and JS from JAVA using Nashorn (replace Rhino)
Annotate local variables, generic types ...
Repeating annotation
Extra
“As a Scala and Java developer, I am not even slightly tempted to replace Scala as my main language for my next project with Java 8.
If I'm forced to write Java, it might better be Java 8,
but if I have a choice, there are so many things (as the OP correctly states) that make Scala compelling for me beyond Lambdas
that just adding that feature to Java doesn't really mean anything to me.
Ruby has Lambdas, so does Python and JavaScript, Dart and I'm sure any other modern language.
I like Scala because of so many other things other than lambdas that a single comment is not enough.
But to name a few (some were referenced by the OP)
Everything is an expression,
For comprehensions (especially with multiple futures, resolving the callback triangle of death in a beautiful syntax IMHO),
Implicit conversions,
Case classes,
Pattern Matching,
Tuples,
The fact that everything has equals and hashcode already correctly implemented (so I can put a tuple, or even an Array as a key in a map),
string interpolation,
multiline string,
default parameters,
named parameters,
built in dependency injection,
most complex yet most powerful type system in any language I know of, type inference (not as good as Haskell, but better than the non existent in Java).
The fact I always get the right type returned from a set of "monadic" actions thanks to infamous things like CanBuildFrom (which are pure genius).
Let's not forget pass by name arguments and the ability to construct a DSL. Extractors (via pattern matching). And many more.
I think Scala is here to stay, at least for Scala developers,
I am 100% sure you will not find a single Scala developer that will say: "Java 8 got lambdas? great, goodbye scala forever!".
Only reason I can think of is compile time and binary compatibility.
If we ignore those two, all I can say is that this just proves how Scala is in the right direction
(since Java 8 lambdas and default interface methods and steams are so clearly influenced)
I do wish however that Scala will improve Java 8 interoperability, e.g. support functional interfaces the same way.
and add new implicit conversions to Java 8 collections as well as take advantage to improvements in the JVM.
I will replace Scala as soon as I find a language that gives me what Scala does and does it better.
So far I didn't find such a language (examined Haskell, Clojure, Go, Kotlin, Ceylon, Dart, TypeScript, Rust, Julia, D and Nimrod, Ruby Python, JavaScript and C#,
some of them were very promising but since I need a JVM language, and preferably a statically typed one, it narrowed down the choices pretty quickly)
Java 8 is by far not even close, sorry. Great improvement, I'm very happy for Java developers that will get "permission" to use it (might be easier to adopt than Scala in an enterprise)
but this is not a reason for a Scala shop to consider moving back to Java.”
So should I leave Scala ?
https://news.ycombinator.com/item?id=7478367
Java has taken "Scala - the good parts"“martin odersky improve Java again (Generics)”

https://www.toptal.com/java/why-you-need-to-upgrade-to-java-8-already

http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html

http://allegro.tech/2014/12/How-to-migrate-to-Java-8.html

https://www.javacodegeeks.com/2014/05/java-8-features-tutorial.html

http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/

https://dzone.com/articles/whats-wrong-java-8-currying-vs

https://dzone.com/articles/whats-wrong-java-8-part-ii

https://dzone.com/articles/whats-wrong-java-8-part-iii

https://dzone.com/articles/whats-wrong-java-8-part-iv

https://dzone.com/articles/whats-wrong-java-8-part-v

https://dzone.com/articles/whats-wrong-java-8-part-vi

https://dzone.com/articles/whats-wrong-java-8-part-vii

http://www.tutorialspoint.com/java8/

http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/

http://www.concretepage.com/java/jdk-8/function-apply-in-java-8
Links

whats new in java 8

  • 1.
  • 2.
     Lambda Expressions  CompletableFuture  Method References  FunctionalInterfaces  Default Methods  Streams  Optional Class  New Date/Time API ... Agenda
  • 3.
    Functional programming: “Lambdaallow us to treat functionality as a method argument (passing functions around)” Syntax: 1) Infers syntax : return / type / {} / () Integer sub = (a, b) → a – b; // no need to write (int a, int b) -> { return a * b; } Arrays.asList( "a", "b").forEach( e → System.out.println( e ) ); // no need to write ((String)e) → ... Lambda (→)
  • 4.
  • 5.
    Lambda (→) 3) Eliminatesthe need of anonymous class 4) Make code more immutable
  • 6.
    Lambda (→) ,the bad parts https://dzone.com/articles/whats-wrong-java-8-part-ii - be aware of auto-boxing System.out.println((x -> x / 100 * (100 + 10)).apply(100)); // java does not know type of X System.out.println((Integer x) -> x / 100 * 100 + 10).apply(100)); // → is a function , java does not know Function type System.out.println(((Function<Integer, Integer>) x -> x / 100 * 100 + 10).apply(100)); * Auto-boxing means automatic convert between primitive and object
  • 7.
    To allow functionsto take lambdas as arguments, Java 8 use “functional interface” which is an interface with has only one abstract method (like Runnable) Functional Interface
  • 8.
    Interface (Default &Static method) Default methods make interfaces similar to scala trait, Interface must implement the default method each implement will inherit it
  • 9.
    java.util.function contains 43methods like: BiFunction<T,U,R> Represents a function that accepts two arguments and produces a result. http://www.tutorialspoint.com/java8/java8_functional_interfaces.htm Predicate<T> // represent a function that return true/false public void calculate(List<Integer> list, Predicate<Integer> predicate) { for(Integer n: list) { if(predicate.test(n)) { //test evaluate predicate on argument System.out.println(n + " "); } } } calculate(list, n-> n%2 == 0 ); Function API http://howtodoinjava.com/java-8/how-to-use-predicate-in-java-8/
  • 10.
    Call methods bytheir names allows us to reference constructors or methods without executing them You can’t pass arguments to methods Reference List names = ArrayList::new; names.add(“a”); names.add(“b”); names.forEach(System.out::println); Car carInstance = Car.create( Car::new ); Car::collide; carInstance::drive; Method reference (::)
  • 11.
  • 12.
    Curring function that returnsa function instead of a result.
  • 13.
    Java 8 bringsnew abilities to work with Collections,Arrays, or I/O resources as input source Stream API offers easy filtering, aggregation, and mapping actions Operations can return stream (pipelined) or result (like collect()) parallelStream : leverage multicore architecture without the need to write any specific code for it (using ForkJoinThreadPool) http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/ https://dzone.com/articles/whats-wrong-java-8-part-iii Stream Stream() / filter() / map() return new stream object Stream() convert collection to stream
  • 14.
    Stream collect() allows usto collect the results of a stream Collectors are used to combine the stream result: List<String>strings = Arrays.asList("a", "", "b", ""); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); String mergedString = strings.stream().filter(string -> string.isEmpty()).collect(Collectors.joining(", "));
  • 15.
    List<Integer> numbers =Arrays.asList(3, 2, 2, 3, 7, 3, 5); IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics(); stats.getMax(); stats.getSum(); stats.getAverage(); Stream – Collectors & Aggregation
  • 16.
    Stream – yetanother example
  • 17.
  • 18.
    CompletableFuture Java 7 hasno interface to get the async task result in the future , there is a way to get the result outside of the future and when its done perform another action Java 8 added Completefuture<T> interface
  • 19.
  • 20.
    Optional is acontainer: it can hold a value of some type T or just be null. It replace null checking and can avoid NullPointerException. Integer value1 = null; Integer value2 = new Integer(10); Optional<Integer> a = Optional.ofNullable(value1); //represent null Optional<Integer> b = Optional.of(value2); Public Integer sum(Optional<Integer> a, Optional<Integer> b){ a.isPresent(); // false Integer value1 = a.orElse(new Integer(5)); // 5 a.orElseGet( () -> 77 ) // instead of parameter it accept a method Integer value2 = b.get(); // 10 return value1 + value2; // 15 } What makes Optional truly appealing are methods such as ifPresent() and orElseThrow() along with map() and filter() which all accept lambda expressions ~ scala monad Optional Class
  • 21.
    java.util.Date & Calendarare not thread safe, developer need to manage timezone issues popular solution JodaTime is 3#party not part of the Java api. Java 8 has 2 implementation : Local / Zoned (which support timezone) LocalDateTime currentTime = LocalDateTime.now(); //2014-12-10 LocalDate.now(Clock.systemUTC()) // Clock object provide access to datetime using timezone // Clock can be used instead of System.currentTimeMillis() and TimeZone.getDefault(). LocalDate nextWeek = currentTime.plus(1, ChronoUnit.WEEKS); //2014-12-17 Period period = Period.between(currentTime, nextWeek); Duration.between( currentTime, nextWeek ).toDays(); LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.TUESDAY)); //2014-12-16 LocalDate date = LocalDate.of(2014, Month.DECEMBER, 12); ZonedDateTime date1 = ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Karachi]"); DateTime (immutable)
  • 22.
  • 23.
    Concurrency how-longadder-performs-better-than-atomiclong Atomic are usedto increment a variable across threads, faster than locks. Java 8 added adders and accumulators which to improve Atomic
  • 24.
  • 25.
    JVM options -XX:PermSizeand –XX:MaxPermSize have been replaced by -XX:MetaSpaceSize and -XX:MaxMetaspaceSize respectively JVM GC1
  • 26.
    Built in base64encoder/decoder Invoke JAVA from JS and JS from JAVA using Nashorn (replace Rhino) Annotate local variables, generic types ... Repeating annotation Extra
  • 27.
    “As a Scalaand Java developer, I am not even slightly tempted to replace Scala as my main language for my next project with Java 8. If I'm forced to write Java, it might better be Java 8, but if I have a choice, there are so many things (as the OP correctly states) that make Scala compelling for me beyond Lambdas that just adding that feature to Java doesn't really mean anything to me. Ruby has Lambdas, so does Python and JavaScript, Dart and I'm sure any other modern language. I like Scala because of so many other things other than lambdas that a single comment is not enough. But to name a few (some were referenced by the OP) Everything is an expression, For comprehensions (especially with multiple futures, resolving the callback triangle of death in a beautiful syntax IMHO), Implicit conversions, Case classes, Pattern Matching, Tuples, The fact that everything has equals and hashcode already correctly implemented (so I can put a tuple, or even an Array as a key in a map), string interpolation, multiline string, default parameters, named parameters, built in dependency injection, most complex yet most powerful type system in any language I know of, type inference (not as good as Haskell, but better than the non existent in Java). The fact I always get the right type returned from a set of "monadic" actions thanks to infamous things like CanBuildFrom (which are pure genius). Let's not forget pass by name arguments and the ability to construct a DSL. Extractors (via pattern matching). And many more. I think Scala is here to stay, at least for Scala developers, I am 100% sure you will not find a single Scala developer that will say: "Java 8 got lambdas? great, goodbye scala forever!". Only reason I can think of is compile time and binary compatibility. If we ignore those two, all I can say is that this just proves how Scala is in the right direction (since Java 8 lambdas and default interface methods and steams are so clearly influenced) I do wish however that Scala will improve Java 8 interoperability, e.g. support functional interfaces the same way. and add new implicit conversions to Java 8 collections as well as take advantage to improvements in the JVM. I will replace Scala as soon as I find a language that gives me what Scala does and does it better. So far I didn't find such a language (examined Haskell, Clojure, Go, Kotlin, Ceylon, Dart, TypeScript, Rust, Julia, D and Nimrod, Ruby Python, JavaScript and C#, some of them were very promising but since I need a JVM language, and preferably a statically typed one, it narrowed down the choices pretty quickly) Java 8 is by far not even close, sorry. Great improvement, I'm very happy for Java developers that will get "permission" to use it (might be easier to adopt than Scala in an enterprise) but this is not a reason for a Scala shop to consider moving back to Java.” So should I leave Scala ? https://news.ycombinator.com/item?id=7478367 Java has taken "Scala - the good parts"“martin odersky improve Java again (Generics)”
  • 28.
     https://www.toptal.com/java/why-you-need-to-upgrade-to-java-8-already  http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html  http://allegro.tech/2014/12/How-to-migrate-to-Java-8.html  https://www.javacodegeeks.com/2014/05/java-8-features-tutorial.html  http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/  https://dzone.com/articles/whats-wrong-java-8-currying-vs  https://dzone.com/articles/whats-wrong-java-8-part-ii  https://dzone.com/articles/whats-wrong-java-8-part-iii  https://dzone.com/articles/whats-wrong-java-8-part-iv  https://dzone.com/articles/whats-wrong-java-8-part-v  https://dzone.com/articles/whats-wrong-java-8-part-vi  https://dzone.com/articles/whats-wrong-java-8-part-vii  http://www.tutorialspoint.com/java8/  http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html  http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/  http://www.concretepage.com/java/jdk-8/function-apply-in-java-8 Links