Lambda expressions, default methods in interfaces, and the new date/time API are among the major new features in Java 8. Lambda expressions allow for functional-style programming by treating functionality as a method argument or anonymous implementation. Default methods add new capabilities to interfaces while maintaining backwards compatibility. The date/time API improves on the old Calendar and Date APIs by providing immutable and easier to use classes like LocalDate.
2. Agenda
❖ New Features in Java language
➢ Lambda Expression
➢ Functional Interface
➢ Interface’s default and Static Methods
➢ Method References
❖ New Features in Java libraries
➢ Stream API
➢ Date/Time API
4. ❖ Unnamed block of code (or an unnamed
function) with a list of formal parameters and
a body.
✓ Concise
✓ Anonymous
✓ Function
✓ Passed around
Lambda Expression
6. Example 1:
Comparator<Person> byAge = new Comparator<Person>(){
public int compare(Person p1, Person p2){
return p1.getAge().compareTo(p2.getAge());
}
};
Lambda Expression
Example 2:
JButton testButton = new JButton("Test Button");
testButton.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ae){
System.out.println(“Hello Anonymous inner class");
}
});
7. Example 1: with lambda
Comparator<Person> byAge =
(Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
Lambda Expression
Example 2: with lambda
testButton.addActionListener(e -> System.out.println(“Hello
Lambda"));
9. (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge());
Lambda Expression
Lambda parameters Lambda body
Arrow
The basic syntax of a lambda is either
(parameters) -> expression
or
(parameters) -> { statements; }
10. ❖ Lambda does not have:
✓ Name
✓ Return type
✓ Throws clause
✓ Type parameters
Lambda Expression
12. Variable scope:
public void printNumber(int x) {
int y = 2;
Runnable r = () -> System.out.println(“Total is:” + (x+y));
new Thread(r).start();
}
Lambda Expression
Free variable: not define in lambda parameters.
Variable scope:
public void printNumber(int x) {
int y = 2;
Runnable r = () ->{System.out.println(“Total is:” + (x+y));
System.out.println(this.toString());};
new Thread(r).start();
}
Not allow:
public void printNumber(int x) {
int y = 2;
Runnable r = () -> {
x++;//compile error
System.out.println(“Total is:” + (x+y))
};
}
25. ● Brand new java.util.function package.
● Rich set of function interfaces.
● 4 categories:
o Supplier
o Consumer
o Predicate
o Function
Add text here...
Functional Interface
26. ● Accept an object and return nothing.
● Can be implemented by lambda
expression.
Add text here...
Consumer Interface
28. Interface Default and Static
Methods
Add text here...
Interface Default and Static Methods
29. static <T> Collection<T>
synchronizedCollection(Collection<T
Interface Default and Static Methods
● Advantages:
- No longer need to provide your own companion utility classes. Instead, you
can place static methods in the appropriate interfaces
- Adding methods to an interface without breaking the existing
implementation
java.util.Collections
java.util.Collection
● Extends interface declarations with two new concepts:
- Default methods
- Static methods
31. Default methods
● Classes implement interface that contains a default method
❏ Not override the default method and will inherit the default method
❏ Override the default method similar to other methods we override in
subclass
❏ Redeclare default method as abstract, which force subclass to override it
32. Default methods
● Solve the conflict when the same method declare in interface or
class
- Method of Superclasses, if a superclass provides a concrete
method.
- If a superinterface provides a default method, and another
interface supplies a method with the same name and
parameter types (default or not), then you must overriding that
method.
33. Static methods
● Similar to default methods except that we can’t override
them in the implementation classes
35. Method References
● Method reference is an important feature related to
lambda expressions. In order to that a method
reference requires a target type context that consists of
a compatible functional interface
36. Method References
● There are four kinds of method references:
- Reference to a static method
- Reference to an instance method of a particular object
- Reference to an instance method of an arbitrary object
of a particular type
- Reference to a constructor
52. // get even numbers
evenNumbers.forEach(i ->
System.out.println(i));
/* Console output
* 2
* 4
* 6
* 8
*/
Add text here...
Stream - forEach()
53. Converting stream to list
List<Integer> numbers =
evenNumbers.collect(Collectors.toList());
Converting stream to array
Integer[] numbers =
evenNumbers.toArray(Integer[]::new);
Add text here...
Stream - Converting to collections
55. What’s new in Date/Time?
Add text here...
Date / Time
56. ● Why do we need a new Date/Time API?
Add text here...
Date / Time
○ Objects are not immutable
○ Naming
○ Months are zero-based
57. ● LocalDate
Add text here...
Date / Time
○ A LocalDate is a date, with a year,
month, and day of the month
LocalDate today = LocalDate.now();
LocalDate christmas2015 = LocalDate.of(2015, 12, 25);
LocalDate christmas2015 = LocalDate.of(2015,
Month.DECEMBER, 25);
58. Java 7:
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
Date dt = c.getTime();
Java 8:
LocalDate tomorrow = LocalDate.now().plusDay(1);
Add text here...
Date / Time
59. ● Temporal adjuster
Add text here...
Date / Time
LocalDate nextPayDay = LocalDate.now()
.with(TemporalAdjusters.lastDayOfMonth());
60. ● Create your own adjuster
TemporalAdjuster NEXT_WORKDAY = w -> {
LocalDate result = (LocalDate) w;
do {
result = result.plusDays(1);
} while (result.getDayOfWeek().getValue() >= 6);
return result;
};
LocalDate backToWork = today.with(NEXT_WORKDAY);
Add text here...
Date / Time
62. Add text here...
References
❖ Java Platform Standard Edition 8 Documentation,
(http://docs.oracle.com/javase/8/docs/)
❖ Java 8 In Action, Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft.
❖ Beginning Java 8 Language Features, Kishori Sharan.
❖ What’s new in Java 8 - Pluralsight
The code is quite not elegant and not easy to read.
Anonymous classes use a bulky syntax. Lambda expressions
use a very concise syntax to achieve the same result.
The body of a lambda expression is a block of code enclosed in braces. Like
a method's body, the body of a lambda expression may declare local variables; use statements including break,
continue, and return; throw exceptions, etc.
A lambda expression does not have a name.
A lambda expression does not have a throws clause. It is inferred from the context of its use
and its body.
A lambda expression cannot declare type parameters. That is, a lambda expression cannot be generic
A lambda expression does not have a explicit return type. It is auto recognized by the compiler from the context of its use and from its body.
Accessing outer scope variables from lambda expressions is very similar to anonymous objects. You can access final variables from the local outer scope as well as instance fields and static variables
So where exactly can you use lambdas? You can use a lambda expression in the context of a
functional interface. Don’t worry if this sounds abstract; we now explain in detail what this means and what a functional interface
is.
Functional Interface is a new term of Java 8
The functional interface is an normal interface with only one abstract method.
Take a look at the example here, the well-known Runnable and Comparator interface are now become functional interface, so what we can see here that the term of functional interface is new but all the interfaces back from previous Java versions are becoming functional interface without any needed of modification.
When we count the abstract method from an interface to check if it’s functional interface or not. The methods from Object class don’t count.
Why some methods of the Object class sometimes are added to an interface? But most of the time and this is the reason because someone would like to redeclared methods from Object class in the interface in order to extend comments from Object’s class in order to give some special semantic and to add javadoc that might be different from Object class.
http://grepcode.com/file_/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Comparator.java/?v=source
By the default, the compiler of Java will automatically check if interface is a functional interface or not.
But for convenience, the functional interface can be annotated inside the code.
It can be annotated by adding @FunctionalInterface on the top of the interface like the example below.
By doing so, the IDE will help you to detect if it is a functional interface before compiler do its job.
In this example, I declared another abstract method in the functional interface and as you can see, with the annotation, the IDE will check and show an error message that this interface is not a functional interface. So you can immediately notice and correct the problem.
With the new term of functional interface defined in java 8.
It also includes a brand new sets of functional interfaces.
All these functional interfaces are defined in new package named java.util.function.
It contains around 43 interfaces and grouped into 4 categories as I listed below: Supplier, consumer, predicate, function.
You will see and use it a lot when you working with Java 8 and lambda expression.
In the scope of this presentation I will not go and explain for every interfaces. Instead, I will pick one of them to give you an example.
Classes implement interface that contains a default method, they can perform following:
- Not override the default method and will inherit the default method- Override the default method similar to other methods we override in subclass- Redeclare default method as abstract, which force subclass to override it
Classes implement interface that contains a default method, they can perform following:
- Not override the default method and will inherit the default method- Override the default method similar to other methods we override in subclass- Redeclare default method as abstract, which force subclass to override it
Let’s talk about why the stream is efficient.
Nowaday, most of computer are using multiple CPUs, so we will take advantages of that to the stream in order to process data parallelly.
Let’s talk about why the stream is efficient.
Nowaday, most of computer are using multiple CPUs, so we will take advantages of that to the stream in order to process data parallelly.
Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
Terminal operations return a result of a certain type instead of again a Stream.
Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
Intermediate operations return the stream itself so you can chain multiple method calls in a row. Let’s learn important ones.
statefull
Date is not a date, but a timestamp, Calendar is mix of dates and times…
have to work with Joda API. But there still have problem with the performance…
this new API is base on Joda and was implemented by joda team