whats new in java 8

28
Dori Waldman

Transcript of whats new in java 8

Page 1: whats new in java 8

Dori Waldman

Page 2: whats new in java 8

Lambda Expressions

CompletableFuture

Method References

Functional Interfaces

Default Methods

Streams

Optional Class

New Date/Time API

...

Agenda

Page 3: whats new in java 8

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

Page 4: whats new in java 8

Lambda (→)2) Function as parameter

Page 5: whats new in java 8

Lambda (→)3) Eliminates the need of anonymous class

4) Make code more immutable

Page 6: whats new in java 8

Lambda (→) , the bad partshttps://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

Page 7: whats new in java 8

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

Page 8: whats new in java 8

Interface (Default & Static method)

Default methods make interfaces similar to scala trait, Interface must implement the default method each implement will inherit it

Page 9: whats new in java 8

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/

Page 10: whats new in java 8

Call methods by their namesallows us to reference constructors or methods without executing themYou 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 (::)

Page 11: whats new in java 8

Method reference vs Lamdba

Page 12: whats new in java 8

Curringfunction that returns a function instead of a result.

Page 13: whats new in java 8

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 objectStream() convert collection to stream

Page 14: whats new in java 8

Streamcollect() 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(", "));

Page 15: whats new in java 8

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

Page 16: whats new in java 8

Stream – yet another example

Page 17: whats new in java 8

Parallel Stream

Page 18: whats new in java 8

CompletableFutureJava 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

Page 19: whats new in java 8

CompletableFuture

Page 20: whats new in java 8

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 nullOptional<Integer> b = Optional.of(value2);

Public Integer sum(Optional<Integer> a, Optional<Integer> b){a.isPresent(); // falseInteger value1 = a.orElse(new Integer(5)); // 5a.orElseGet( () -> 77 ) // instead of parameter it accept a method

Integer value2 = b.get(); // 10return 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

Page 21: whats new in java 8

java.util.Date & Calendar are not thread safe, developer need to manage timezone issuespopular 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)

Page 22: whats new in java 8

DateTime

Page 23: whats new in java 8

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

Page 24: whats new in java 8

Concurrency

Page 25: whats new in java 8

JVM options -XX:PermSize and –XX:MaxPermSize have been replaced by -XX:MetaSpaceSize and -XX:MaxMetaspaceSize respectively

JVM

GC1

Page 26: whats new in java 8

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

Page 27: whats new in java 8

“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)”

Page 28: whats new in java 8

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