2. 2CONFIDENTIAL
• Java 8 General Overview
• Lambdas and Functional Interfaces
• Stream API
• Method References
• Interface’s Default and Static Methods
• Optional
• Date/Time API
• Nashorn, JS Engine
Agenda
3. 3CONFIDENTIAL
Java installing problems
Please, pay attention when installing Java 8.
Note! Tomcat 7.0.x does not work with Java 8:
So make sure your JAVA_HOME is not pointing to Java 8 SDK directory or you will get
bunch of errors. Change your JAVA_HOME or configure your project properly.
4. 4CONFIDENTIAL
Overview
JAVA 8 RELEASE (March 18, 2014)
Optional (value wrapper)Lambdas &
Method references
METHODS INSIDE JAVA INTERFACES
Default methods New Utilities
Stream API Date Time API Nashorn, JS Engine
6. 6CONFIDENTIAL
Lambdas (closures) syntax
Each lambda expression has two parts separated by an arrow token: the left hand side is our method
arguments, and the right hand side is what we do with those arguments (business logic)
8. 8CONFIDENTIAL
Motivation
• Shorter way of writing an implementation of a method for later execution.
• Provides simple horizontal solution that solves the "vertical problem" presented by inner classes.
• Lambda expressions are designed to allow code to be streamlined.
• Lambdas expressions do not produce any extra classes the way nested classes do.
9. 9CONFIDENTIAL
Method reference
Oracle reference guide
“You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does
nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name.”
Kind Example
Reference to a static method ContainingClass::staticMethodName
Reference to an instance method of
a particular object
containingObject::instanceMethodName
Reference to an instance method of
an arbitrary object of a particular
type
ContainingType::methodName
Reference to a constructor ClassName::new
Kinds of methods referencesExample
11. 11CONFIDENTIAL
Pre-Built function library (java.util.function)
There are a lot of re-usable functional requirements that can be captured by functional interfaces and
lambdas. The designers of Java 8 have captured the common use cases and created a library of functions
… etc.
13. 13CONFIDENTIAL
Hello, Streams
Streams let you process data in a declarative way. We do not say how to process the data, we
just say what to do with the data.
Let’s say we need to find all transactions of type ‘grocery’ and return a list of transaction
IDs sorted in decreasing order of transaction value.
15. 15CONFIDENTIAL
Streams versus Collections
Q. What is the difference?
Q. So when should I use streams and why?
Q. On demand?
A. In a nutshell, collections are about data and streams are about computations.
A. Use streams when things are computed. A collection is an in-memory data structure, which holds all the
values that the data structure currently has—every element in the collection has to be computed before it can
be added to the collection. In contrast, a stream is a conceptually fixed data structure in which elements are
computed on demand.
A. Yes, look:
limit(2) uses short-
circuiting;
we need to process
only part of the
stream, not all of
it.
16. 16CONFIDENTIAL
So…
Stream as an abstraction for expressing
efficient, SQL-like operations on a
collection of data.
The Streams API will internally
decompose your query to leverage the
multiple cores on your computer.
18. 18CONFIDENTIAL
Optional
A. “… a container object which may or may not contain a non-null value...” Java 8 Reference Guide
Q. Of course, the null reference is the source of many problems. But how does Optional solve them?
Q. What is it?
Q. Why do we need them?
A. Because "Null sucks." Doug Le (a professor of computer science)
A. Enough talking; let's see some code!
19. 19CONFIDENTIAL
java.util.Optional usage
Do Something If a Value Is Present
Default Values and Actions
Creating of Optional
Old style
New style
Old style
New style
Rejecting Certain Values Using the filter Method
Old style
New style
21. 21CONFIDENTIAL
What are default methods?
Default methods enable you to add new functionality to the interfaces of your libraries and ensure
backward compatibility with code written for older versions of those interfaces.
The forEach isn’t declared by java.util.List nor the java.util.Collection interface yet. The solution would
be to just add the new method to the existing interface and provide the implementation where required in
the JDK. But, once published, it is impossible to add methods to an interface without breaking the existing
implementation
Syntax
22. 22CONFIDENTIAL
Extending interfaces with default methods
When you extend an interface that contains a default method, you can do the following:
Not mention the default method at all, which lets inherit the default method.
Redeclare the default method, which makes it abstract.
Redefine the default method, which overrides it.
23. 23CONFIDENTIAL
Tricks
“What if the class implements two interfaces and both those interfaces define a default method with
the same signature?”
24. 24CONFIDENTIAL
Static methods
Like static methods in classes, you specify that a method definition in an interface is a static method
with the static keyword at the beginning of the method signature. All method declarations in an
interface, including static methods, are implicitly public, so you can omit the public modifier.
Applications. Examples
The Comparator interface has been enhanced with this ability with the default method reversed:
26. 26CONFIDENTIAL
Date API. Core ideas.
The new API is driven by three core ideas:
Domain-driven design. The new API models its domain very precisely with classes that represent
different use cases for Date and Time closely. This differs from previous Java libraries that were quite
poor in that regard.
Immutable-value classes. One of the serious weaknesses of the existing formatters in Java is that they aren’t
thread-safe. This puts the burden on developers to use them in a thread-safe manner and to think about
concurrency problems in their day-to-day development of date-handling code. The new API avoids this issue
by ensuring that all its core classes are immutable and represent well-defined values.
Separation of chronologies. The new API allows people to work with different calendaring systems in order to
support the needs of users in some areas of the world, such as Japan or Thailand, that don’t necessarily follow
ISO-8601. It does so without imposing additional burden on the majority of developers, who need to work only
with the standard chronology
27. 27CONFIDENTIAL
Date API. Creating.
The first classes you will probably encounter when using the new API are LocalDate and LocalTime.
Standard Java getter conventions are used in order to obtain values from Java SE 8 classes
28. 28CONFIDENTIAL
Date API. Creating (2).
There are also methods for calculations based on the different fields.
The new API also has the concept of an adjuster— a block of code that can be used to wrap
up common processing logic
29. 29CONFIDENTIAL
Date API. Go ahead.
The new API supports different precision time points by offering types to represent a date, a
time, and date with time, but obviously there are notions of precision that are more fine-
grained than this.
Time Zones
A time zone is a set of rules, corresponding to a region in which the standard time is the same
Before starting I want pay your attention to some problems you might have when installing new Java 8 SDK. If you use any Tomcat of version 7 on your local machine you will probably fail to run it on top of Java 8. Because Apache Tomcat 7 is not compatible with Java 8. So there are several options: you have to update your Tomcat. Or if you do not want any updates, make sure your JAVA_HOME is not pointing to Java 8 SDK directory.
So the first Java 8 release was at the 18-th of March in 2014. Later on Oracle released different security updates, different patches and so on.
The main features of Java 8 are:
Lambda expression - Adds functional processing capability to JAVA.
Optional - Emphasis on best practices, to handle null values properly.
Default method - Interface to have default method implementation.
New Tools - New compiler tools and utilities are added like jdeps to figure out the dependencies.
Stream API - New stream API to facilitate pipeline processing.
Date Time API - Improved date time api.
Nashorn , JavaScript Engine - A JAVA based engine to execute JavaScript code.
This is Duke
Each lambda expression has two parts separated by an arrow token: the left hand side is our method arguments, and the right hand side is what we do with those arguments (business logic)
Let’s take a look at the example below.
1
2 as you may have noticed we omitted types of the arguments and that OK. You will understand it later.
3 If your business logic is much more complex than just a line of code you may use curly braces.
4 no args
And it’s not even about lines of code.
Lambdas expressions do not produce any extra classes the way inner classes do – so you don’t overheat JVM with a lot of class files it should load into memory. Lambdas has some low-level implementation. It is not just a syntax sugar over nested classes.
Useful info:
When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions
As mentioned in the section Nested Classes, nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code. Local classes, anonymous classes, and lambda expressions also impart these advantages; however, they are intended to be used for more specific situations:
Local class: Use it if you need to create more than one instance of a class, access its constructor, or introduce a new, named type (because, for example, you need to invoke additional methods later).
Anonymous class: Use it if you need to declare fields or additional methods.
Lambda expression:
Use it if you are encapsulating a single unit of behavior that you want to pass to other code. For example, you would use a lambda expression if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error.
Use it if you need a simple instance of a functional interface and none of the preceding criteria apply (for example, you do not need a constructor, a named type, fields, or additional methods).
Nested class: Use it if your requirements are similar to those of a local class, you want to make the type more widely available, and you don't require access to local variables or method parameters.
Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.
You use lambda expressions to create anonymous methods.
Sometimes a lambda expression does nothing but call an existing method.
In those cases, it's often clearer to refer to the existing method by name. So Oracle has just created a so called syntax sugar.
There different kinds of method references…
Lambdas expressed single method classes. They can either be assigned to a variable or passed around to other methods just like we pass data as arguments. And here where functional interfaces come into. Conceptually, a functional interface has exactly one abstract method. Well know classes: (e.g. Runnable, Callable, Comparator).
In Java 8 all the mentioned classes are marked with @FunctionalInterface annotation. It just a marker you may not use it. An informative annotation used to indicate that an interface is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method
1 We tell the compiler ‘I want to implement check method from ITrade so to someone else can pass me as arguments to another method’
2 The second one is the same.
3 We do not change the signature of our method, we just pass different trend lambdas
http://radar.oreilly.com/2014/08/java-8-functional-interfaces.html
http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html
Streams let you process data in a declarative way. We do not say how to process the data, we just say what to do with the data.
Example
…
By the way Stream operations that can be connected are called intermediate operations.
Power of parallel streams
…
(in the end)
This is because limit(2) uses short-circuiting; we need to process only part of the stream, not all of it, to return a result.
List<String> phrases = Arrays.asList( "sporadic perjury", "confounded skimming", "incumbent jailer", "confounded jailer"); List<String> uniqueWords = phrases .stream() .flatMap(phrase -> Stream.of(phrase.split(" +"))) .distinct() .sorted() .collect(Collectors.toList()); System.out.println("Unique words: " + uniqueWords);... and the output:
Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]
http://geekabyte.blogspot.co.il/2015/01/using-optional-effectively-in-java-8.html
http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
You use orElse() in situation where you want to have an alternative value in case T is null.
orElseGet() method is similar to orElse(), but instead of providing an alternative, should in case null is encountered, you provide code which can be used to generate the alternative value .
orElseThrow() comes in handy when you want to decide which exception to throw in case a null value is encountered.
Just read!
http://zeroturnaround.com/rebellabs/java-8-explained-default-methods/
http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
The primary goal of default methods is to enable an evolution of standard JDK interfaces and provide a smooth experience when we finally start using lambdas in Java 8. Who knows, maybe in the future we will see some more applications of default methods for API design.
This example demonstrates how the Comparator interface has been enhanced with default methods, static methods, lambda expressions, and method references to create more expressive library methods whose functionality programmers can quickly deduce by looking at how they are invoked. Use these constructs to enhance the interfaces in your libraries.
http://openjdk.java.net/projects/nashorn/
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
Nashorn's goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM.
If you have any questions, please do not hesitate to ask me. I will send you homework later.