2. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
3. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
4. Lambda Expressions
• Simply, It is a method to eliminate anonymous classes
and nested calling functions like the action should be
taken when someone clicks a button.
5. Lambda Expressions
• Why Lambda Expressions?
• Ex:
for (int i = 0; i < names.size(); i++)
{
System.out.println(names.get(i));
}
6. Lambda Expressions
• Why Lambda Expressions?
• It is Simple
names.foreach
(name->System.out.println(name))
9. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
10. Method References
• It is easy-to-read lambda expressions for methods that
already have a name by referring to the existing method
by name.
11. Method References
• Why Method References?
• If there is a function in person object compares ages.
Arrays.sort(personsArray, (a, b) ->
Person.compareByAge(a, b) );
When using Method References
Arrays.sort(personsArray, Person::compareByAge);
12. Method References
• Kinds of Method References
Kind Example
Reference to an instance method of a
particular object
persons.foreach
(System.out.println(preson::getEmail))
Reference to a static method
Arrays.sort(personsList,
Person::compareByAge);
Reference to an instance method of an
arbitrary object of a particular type
Arrays.sort(stringArray,
String::compareToIgnoreCase);
Reference to a constructor
transferElements(personsList,
HashSet<Person>::new);
13. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
14. Streams
• It is a sequence of elements. Unlike a collection, it is not
a data structure that stores elements but it carries values
from it.
15. Streams
• Why Streams?
• Parallelism is the main target today.
big data multicore
cloud
computing
16. Streams
• Why Streams?
• Parallelism is the main target today.
for (int i = 0; i < names.size(); i++)
{
System.out.println(names.get(i));
}
Ques: How to use Parallelism?
17. Streams
• Why Streams?
• Simply you can Choose between Serial or parallel.
names.stream().foreach
(name->System.out.println(name))
names.parallelStream().foreach.
(name->System.out.println(name))
18. Streams
• Why Streams?
• It makes a pipeline (a sequence of aggregate operations)
names.stream
.filter(e -> e.equals(“java”))
.forEach(e -> System.out.println(e));
19. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
20. Default methods
• It enables you to add new functionality to the interfaces
of your libraries and ensure compatibility with code
written for older versions of those interfaces.
21. Default methods
• Why Default methods?
• Consider the following interface TimeClient.
public interface TimeClient {
void setTime(int hour, int minute, int second);
void setDate(int day, int month, int year);
}
22. Default methods
• Why Default methods?
• The following class SimpleTimeClient impelements it.
public class SimpleTimeClient implements TimeClient {
void setTime(int hour, int minute, int second){
//some code }
void setDate(int day, int month, int year){
//some code }
}
23. Default methods
• Why Default methods?
• How to add new functionality to the TimeClient interface?
24. Default methods
• Why Default methods?
• How to add new functionality to the TimeClient interface?
public interface TimeClient {
………
String getDateZone(String zoneString);
}
25. Default methods
• Why Default methods?
• How to add new functionality to the TimeClient interface?
public class SimpleTimeClient implements
TimeClient{
………
String getDateZone(String zoneString){
// some code
}
}
26. Default methods
• Default Methods
• You can define default method in interfaces instead.
public interface TimeClient {
………
default getDateZone(String zoneString) {
// some code
}
}
27. Default methods
• Static Methods
• Also, you can define static methods in interfaces.
public interface TimeClient {
………
static ZoneId getZoneId (String zoneString) {
// some code
}
}
28. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
29. Date and Time API
• Why do we need a new date and time library?
• (java.util.Date and SimpleDateFormatter) aren’t thread-safe.
• Poor API design. For example, years in java.util.Date start at
1900, months start at 1, and days start at 0—not very intuitive.
• Inadequate support for the date and time use cases of ordinary
developers.
30. Date and Time API
• Why do we need a new date and time library?
• (java.util.Date and SimpleDateFormatter) aren’t thread-safe.
• Poor API design. For example, years in java.util.Date start at
1900, months start at 1, and days start at 0—not very intuitive.
• Inadequate support for the date and time use cases of ordinary
developers.
These issues, and several others, have led to “Time API”.
31. Date and Time API
• Thread Safe
• The classes are immutable “no setters”.
LocalDateTime timePoint = LocalDateTime.now( );
// it is returning a new object instead of setting
LocalDateTime thePast = timePoint.withDayOfMonth(
10).withYear(2010);
/* You can use direct manipulation methods,
or pass a value and field pair */
LocalDateTime yetAnother = thePast.plusWeeks(
3).plus(3, ChronoUnit.WEEKS);
32. Date and Time API
• Periods
• Represents values such as “3 years 2 months and 1 day”
Period period = Period.of(3, 2, 1);
// You can modify the values of dates using periods
LocalDateTime newDate = timePoint.plus(period);
33. Date and Time API
• Durations
• Represents values such as “3 seconds and 5 nanoseconds”
Duration duration = Duration.ofSeconds(3, 5);
// You can modify the values of dates using durations
LocalDateTime newDate = timePoint.plus(duration);
34. Date and Time API
• Time Truncation
• The truncatedTo method allows you to truncate a value to a field
LocalTime truncatedTime =
time.truncatedTo(ChronoUnit.SECONDS);
35. Date and Time API
• Time Zones
• You can specify the zone id when creating a zoned date time
ZoneId id = ZoneId.of("Europe/Paris");
ZonedDateTime zoned = ZonedDateTime.of(timePoint,
id);
Hint: There is an existing time zone class in Java—java.util.TimeZone—
but it isn’t used by Java SE 8 because Time API classes are immutable
and time zone is mutable.
36. Date and Time API
• Chronologies
• Is the concept of representing a factory for calendaring system.
Chronology:
ChronoLocalDate
ChronoLocalDateTime
ChronoZonedDateTime
37. Date and Time API
• Chronologies
• Is the concept of representing a factory for calendaring system.
Chronology:
ChronoLocalDate
ChronoLocalDateTime
ChronoZonedDateTime
These classes are there purely for developers who are working on
highly internationalized applications
38. Date and Time API
• HijrahChronology [Class Implements Chronology]
• Follows Hijrah calendar system observation “new moon
occurrence”
Chronology ID Calendar Type Locale extension Description
Hijrah-umalqura islamic-umalqura
ca-islamic-umalqura
Islamic - Umm
Al-Qura calendar
of Saudi Arabia
39. Date and Time API
• HijrahDate
• HijrahDate is created bound to a particular HijrahChronology
HijrahChronology calendar =
HijrahChronology.INSTANCE;
HijrahDate date=calendar.dateNow();
// result is Hijrah-umalqura AH 1436-01-12
//”rtl printing”
40. Date and Time API
• HijrahDate
• HijrahDate is created bound to a particular HijrahChronology
HijrahChronology calendar =
HijrahChronology.INSTANCE;
HijrahDate date=calendar.dateNow();
date.minus(2, ChronoUnit.DAYS);
date.plus(3, ChronoUnit.YEARS);
HijrahDate secondDate=calendar.date(1435, 4, 1);//rtl
date.isAfter(secondDate);
date.isBefore(secondDate);
41. What's New in JDK 8
• Lambda Expressions
• Method references
• Streams
• Default methods
• Date and Time API
• Nashorn engine
42. Nashorn engine
• Nashorn is an embedded scripting engine inside Java
applications and how Java types can be implemented and
extended from JavaScript, providing a seamless
integration between the two languages.
43. Nashorn engine
• What’s new in Nashorn
• run JavaScript programs from the command line with tool jjs
var hello = function() {
print("Hello Nashorn!");
};
hello();
Evaluating it is as simple as this:
$ jjs hello.js
$ Hello Nashorn!
44. Nashorn engine
• What’s new in Nashorn
• Embedding Oracle Nashorn in java Apps
public class Hello {
public static void main(String... args) throws
Throwable {
ScriptEngineManager engineManager = new
ScriptEngineManager();
ScriptEngine engine =
engineManager.getEngineByName("nashorn");
engine.eval("function sum(a, b) { return a + b; }");
System.out.println(engine.eval("sum(1, 2);")); } }
45. Nashorn engine
• What’s new in Nashorn
• Java seen in javascript
Java objects can be instantiated using the new
operator:
var file = new java.io.File("sample.js");
print(file.getAbsolutePath());
print(file.absolutePath);
46. Nashorn engine
• What’s new in Nashorn
• Java seen in javascript [ dealing with collections]
var stack = new java.util.LinkedList();
[1, 2, 3, 4].forEach(function(item) {
stack.push(item); });
tour through the new Java 8 stream APIs to sort the
collection:
var sorted = stack.stream().sorted().toArray();
47. Nashorn engine
• What’s new in Nashorn
• Java seen in javascript [ Imports]
importClass(java.util.HashSet);
var set = new HashSet();
importPackage(java.util);
var list = new ArrayList();
48. Nashorn engine
• What’s new in Nashorn
• Java seen in javascript [JavaImporter] .
var CollectionsAndFiles = new JavaImporter(
java.util, java.i);
It is not global as import classes:
with (CollectionsAndFiles) {
var files = new LinkedHashSet();
files.add(new File("Plop"));
files.add(new File("Foo"));}
49. Nashorn engine
• What’s new in Nashorn
• The Java.type used to reference to precise Java types.
var LinkedList = Java.type( "java.util.LinkedList");
var primitiveInt = Java.type( "int");
var arrayOfInts = Java.type( "int[]");
var list = new LinkedList;
var a = new arrayOfInts(3);
50. Nashorn engine
• What’s new in Nashorn
• Extending java type
var iterator = new java.util.Iterator({
i: 0,
hasNext: function() {
return this.i < 10; },
next: function() {
return this.i++; }
});
51. Nashorn engine
• What’s new in Nashorn
• Support Lambda Expression
var odd = list.stream().filter( function(i) { return
i % 2 == 0; });
Like this:
var odd = list.stream().filter( function(i) i % 2 ==
0);
Oracle’s JDK include a command-line tool called jjs. It can be found in the bin/ folder of a JDK installation along with the well-known java, javac, or jar tools.
Mozilla Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine.