SlideShare a Scribd company logo
Introduction Java 8 with emphasis on lambda expressions and streams
Emiel Paasschens en Marcel Oldenkamp, 10 april 2014
Java SIG
Agenda
• What's new in Java 8
– Type annotations
– Reflection
– Compact profiles
– New Date and Time API
– Optional Class
• Lambda expressies
• Streams
– Nashorn
– Base64
– No More Permanent Generation
– Default methods on interfaces
– Static methods on interfaces
3
What's New in JDK 8
Type annotations
• Type Annotations are annotations that can be placed anywhere you use a
type. This includes the new operator, type casts, implements clauses
and throws clauses. Type Annotations allow improved analysis of Java
code and can ensure even stronger type checking.
• Java 8 only provides the ability to define these types of annotations. It is
then up to framework and tool developers to actually make use of it.
4
What's New in JDK 8
Method parameter reflection
• Existing reflection methods
– Get a reference to a Class
– From the Class, get a reference to a Method by calling getDeclaredMethod()
or getDeclaredMethods() which returns references to Method objects
• New
– From the Method object, call getParameters() which returns an array of Parameter objects
– On the Parameter object, call getName()
• Only works if code is compiled with -parameters compiler option
5
What's New in JDK 8
Compact profiles
• Three Compact Profiles 1, 2, 3
– contain predefined subsets of the Java SE platform
– reduced memory footprint, allows applications to run on resource-constrained
devices (mobile, wearable such as glass, watch )
– compact profiles address API choices only; they are unrelated to the Java virtual
machine (Jigsaw), the language, or tools.
6
What's New in JDK 8
New Date and Time API
Java 8 introduces a new Date/Time API that is safer, easier to read, and
more comprehensive than the previous API. Java‟s Calendar implementation
has not changed much since it was first introduced and Joda-Time is widely
regarded as a better replacement. Java 8‟s new Date/Time API is very
similar to Joda-Time.
For example, define the time 8 hours from now:
Before Java 8:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 8);
cal.getTime(); // actually returns a Date
Java 8:
LocalTime now = LocalTime.now();
LocalTime later = now.plus(8, HOURS);
7
What's New in JDK 8
Optional Class
Java 8 comes with the Optional class in the java.util package for avoiding
null return values (and thus NullPointerException). It is very similar to Google
Guava‟s Optional and Scala‟s Option class.
You can use Optional.of(x) to wrap a non-null value,
Optional.empty() to represent a missing value,
or Optional.ofNullable(x) to create an Optional from a reference that may or
may not be null.
After creating an instance of Optional, you then use isPresent() to determine if
there is a value and get() to get the value. Optional provides a few other helpful
methods for dealing with missing values:
orElse(T) Returns the given default value if the Optional is empty.
orElseGet(Supplier<T>) Calls on the given Supplier to provide a value if the
Optional is empty.
orElseThrow(Supplier<X extends Throwable>) Calls on the given Supplier
for an exception to throw if the Optional is empty.
8
What's New in JDK 8
Nashorn
Nashorn replaces Rhino as the default JavaScript engine for the Oracle JVM.
Nashorn is much faster since it uses the invokedynamic feature of the JVM. It also
includes a command line tool (jjs).
You can run JavaScript files from the command line (java bin in your PATH):
$ jjs script.js
Running jjs with the -scripting option starts up an interactive shell:
jjs> var date = new Date()
jjs> print("${date}")
You can also run JavaScript dynamically from Java:
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval("function p(s) { print(s) }");
engine.eval("p('Hello Nashorn');");
engine.eval(new FileReader('library.js'));
9
What's New in JDK 8
Base64
Until now, Java developers have had to rely on third-party libraries for encoding
and decoding Base-64. Since it is such a frequent operation, a large project will
typically contain several different implementations of Base64. For example:
Apache commons-codec, Spring, and Guava all have separate implementations.
For this reason, Java 8 has java.util.Base64. It acts like a factory for Base64
encoders and decoders and has the following methods:
getEncoder()
getDecoder()
getUrlEncoder()
getUrlDecoder()
The URL Base-64 Encoder provides an encoding that is URL and Filename safe.
10
What's New in JDK 8
No More Permanent Generation
Most allocations for the class metadata are now allocated out of native memory.
This means that you won‟t have to set the “XX:PermSize” options anymore (they
don‟t exist).
This also means that you will get a
java.lang.OutOfMemoryError: Metadata space
error message instead of
java.lang.OutOfMemoryError: Permgen space
when you run out of memory.
This is part of the convergence of the Oracle JRockit and HotSpot JVMs.
The proposed implementation will allocate class meta-data in native memory and move interned
Strings and class statics to the Java heap. [http://openjdk.java.net/jeps/122]
11
What's New in JDK 8
Default methods on interfaces
Default methods can be added to any interface. Like the name implies, any class
that implements the interface but does not override the method will get the default
implementation.
interface Bar {
default void talk() {
System.out.println("Bar!");
}
}
class MyBar implements Bar {
}
MyBar myBar = new MyBar();
myBar.talk();
12
What's New in JDK 8
Default methods on interfaces
With a multiple inherited default method, you have to implement!
interface Foo {
default void talk() {
System.out.println("Foo!");
}
}
interface Bar {
default void talk() {
System.out.println("Bar!");
}
}
class FooBar implements Foo, Bar {
@Override
void talk() {
Foo.super.talk();
}
}
13
What's New in JDK 8
Static methods on interfaces
The ability to add static methods to interfaces is a similar change to the Java
language:
This makes “helper” methods easier to find since they can be located directly on
the interface, instead of a different class such as StreamUtil or Streams.
Here‟s an example in the new Stream interface:
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
14
What's New in JDK 8
Others
• JDK 8 includes Java DB 10.10 (Apache Derby open source database)
• The Java SE 8 release contains Java API for XML Processing (JAXP) 1.6
• http://www.oracle.com/technetwork/java/javase/8-whats-new-
2157071.html
15
Lambda Expressions
• Lambda Expressions
– A new language feature.
– Enable you to treat functionality as a method argument, or code as data.
– Lambda expressions let you express instances of single-method interfaces (referred
to as functional interfaces) more compactly.
16
Lambda Expressions
• What is a Lambda Expression?
– A lambda expression is an anonymous function. See it as a method without a
declaration. (no access modifier, return value declaration, and name)
– „functional expression treated as a variable‟ .
– Ability to pass “functionality” as an argument, previous only possible using inner
class.
17
Lambda Expressions
• What is a Lambda Expression?
– A lambda expression is an anonymous function. See it as a method without a
declaration. (no access modifier, return value declaration, and name)
– „functional expression treated as a variable‟ .
– Ability to pass “functionality” as an argument, previous only possible using inner
class.
• Why do we need lambda expressions?
– Convenience. Write a method in the same place you are going to use it.
– In the „old days‟ Functions where not important for Java. On their own they cannot
live in Java world. Lambda Expressions makes a Function a first class citizen, they
exists on their own.
– They make it easier to distribute processing of collections over multiple threads.
• How do we define a lambda expression?
– (Parameters) -> { Executed code }
18
Structure of Lambda
Expressions
• A lambda expression can have zero, one or more parameters.
• The type of the parameters can be explicitly declared or it can be inferred from the context.
is same as just
• Parameters are enclosed in parentheses and separated by commas.
• When there is a single parameter, parentheses are not mandatory
• The body of the lambda expressions can contain zero, one or more statements.
• If body of lambda expression has single statement curly brackets are not mandatory and
the return type of the anonymous function is the same as that of the body expression.
• When there is more than one statement in body than these must be enclosed in curly
brackets (a code block) and the return type of the anonymous function is the same as the
type of the value returned within the code block, or void if nothing is returned.
or or
19
Functional Interface
• Functional Interface is an interface with just one abstract method declared in it.
(so the interface may have other default and static methods)
• Indicated by the informative annotation @FunctionalInterface
(the compiler will give an error if there are more abstract methods)
• java.lang.Runnable is an example of a Functional Interface. There is only one
method void run().
• Other examples are Comparator and ActionListener.
20
Functional Interface –
„the old way‟
• Functional Interface is an interface with just one abstract method declared in it.
• Example of assigning „on the fly‟ functionality (the old way)
21
Functional Interface example
Runnable using Lambda
NEW:
• Example of assigning „on the fly‟ functionality (the new way)
• A lambda expression evaluates to an instance of a functional interface
OLD:
22
Functional Interface example
Runnable using Lambda
Even shorter notation:
23
Functional Interface example
ActionListener using Lambda
NEW:
Example of a lambda expression with parameters
(functional interface actionlistener)
OLD:
24
Comparable using Lambda
25
Predefined Functional Interfaces
Java 8 comes with several functional interfaces in package java.util.function:
• Function<T,R> Takes an object of type T and returns R.
• Supplier<T> Just returns an object of type T.
• Predicate<T> Returns a boolean value based on input of type T.
• Consumer<T> Performs an action with given object of type T.
• BiFunction Like Function but with two parameters.
• BiConsumer Like Consumer but with two parameters.
It also comes with several corresponding interfaces for primitive types, e.g:
• IntFunction<R>
• IntSupplier
• IntPredicate
• IntConsumer
26
Method References
Since a lambda expression is like a method without an object attached, wouldn‟t it
be nice if we could refer to existing methods instead of using a lamda expression?
This is exactly what we can do with method references:
public class FileFilters {
public static boolean fileIsPdf(File file) {/*code*/}
public static boolean fileIsTxt(File file) {/*code*/}
public static boolean fileIsRtf(File file) {/*code*/}
}
List<File> files = new LinkedList<>(getFiles());
files.stream().filter(FileFilters::fileIsRtf)
.forEach(System.out::println);
27
Method References
Method references can point to:
• Static methods (ie. previous slide).
• Instance methods (ie. 2 below).
• Methods on particular instances (ie. line 4 below).
• Constructors (ie. TreeSet::new)
For example, using the new java.nio.file.Files.lines method:
1 Files.lines(Paths.get("Nio.java"))
2 .map(String::trim)
3 .filter(s -> !s.isEmpty())
4 .forEach(System.out::println);
28
Collections - Streams
• In Java <= 7 collections can only be manipulated through iterators
• Verbose way of saying:
– "the sum of the weights of the red blocks in a collection of blocks“
• Programmer expresses how the computer should execute an algorithm
• But, programmer is usually only interested in what the computer should calculate
• To this end, other languages already provide what is sometimes called a pipes-and-
filters-based API for collections.
– Like linux: cat diagnostic.log | grep error | more
29
Collections - Streams
• Java is extended with a similar API for its collections using filter and
map, which take as argument a (lambda) expression.
• Classes in the new java.util.stream package provide a Stream API to
support functional-style operations on streams of elements.
• The Stream API is integrated into the Collections API, which enables bulk
operations on collections, such as sequential or parallel map-reduce
transformations.
30
Collections - Streams
Stream can be used only once!
Stream consists of:
1. One source
2. Zero or more intermediate operations
(e.g. filter, map)
3. One terminal operation
(forEach, reduce, sum)
31
Collections - Streams
Some examples of sources:
• From a Collection via the stream() and parallelStream() methods;
• From an array via Arrays.stream(Object[]);
• From static factory methods on the stream classes, such as
Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object,
UnaryOperator);
• The lines of a file can be obtained from BufferedReader.lines();
• Streams of file paths can be obtained from methods in Files;
• Streams of random numbers can be obtained from Random.ints();
• Numerous other stream-bearing methods in the JDK, including
BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and
JarFile.stream().
32
Collections - Streams
Intermediate operations:
• distinct() Remove all duplicate elements using equals method
• filter(Predicate<T> predicate) Filters elements using predicate
• limit(long maxSize) Truncates stream to first elements till maxSize
(can be slow when parallel processing on ordered parallel pipelines)
• map(Function<T,R> mapper) Map/convert object to other object
• peek(Consumer<T> action) Apply given method on each element
tip: useful for debugging: .peek(o -> System.out.println("o: " + o))
• skip(long n) Remove first n element from Stream
(can be slow when parallel processing on ordered parallel pipelines)
• sorted(Comparator<T> comparator) Sort the stream with given Comparator
33
Collections - Streams
Terminal operations:
• boolean allMatch,anyMatch,noneMatch(Predicate<T> predicate)
• long count() The count of all elements.
• Optional<T> findAny() Return any element (or empty Optional)
• Optional<T> findFirst() Return 1st element (or empty Optional)
• Optional<T> min,max(Comparator<T> comparator)
Return first or last element according to comparator
• void forEach(Consumer<T> action) Performs action on each element
• T reduce(T identity, BinaryOperator<T> accumulator)‟Combine‟ all
elements T to one final result T.
Sum, min, max, average, and string concatenation are all special cases of
reduction, e.g. Integer sum = integers.reduce(0, (a, b) -> a+b);
PS The methods sum() and average() are available on „specialized‟ Streams
IntStream, LongStream and DoubleStream
34
Collections - Streams
Terminal operations:
• collect(Supplier<R> supplier, BiConsumer<R,T> accumulator,
BiConsumer<R,R> combiner)
Performs operation accumulator on all elements of type T resulting into result R.
class Averager implements IntConsumer {
private int total = 0;
private int count = 0;
public double average() {
return count > 0 ? ((double) total)/count : 0;
}
public void accept(int i) { total += i; count++; }
public void combine(Averager other) {
total += other.total;
count += other.count;
}
}
ages.collect(Averager::new, Averager::accept, Averager::combine);
35
More information
More info
AMIS Blog:
• http://technology.amis.nl/2013/10/03/java-8-the-road-to-lambda-expressions/
• http://technology.amis.nl/2013/10/05/java-8-collection-enhancements-leveraging-lambda-
expressions-or-how-java-emulates-sql/
Others:
• https://leanpub.com/whatsnewinjava8/read#leanpub-auto-default-methods
• http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
• http://java.dzone.com/articles/why-we-need-lambda-expressions
• http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
• http://www.angelikalanger.com/Lambdas/Lambdas.html
• http://www.coreservlets.com/java-8-tutorial/#streams-2
• http://java.dzone.com/articles/interface-default-methods-java
36

More Related Content

PDF
Java 8 Lambda Expressions & Streams
PDF
Java 8 features
PPTX
Java 8 lambda
PPTX
Java 8 Lambda and Streams
PPTX
Java 8 Features
PPTX
The Dark Side Of Lambda Expressions in Java 8
PPTX
java 8 new features
PPTX
Lambda Expressions in Java 8
Java 8 Lambda Expressions & Streams
Java 8 features
Java 8 lambda
Java 8 Lambda and Streams
Java 8 Features
The Dark Side Of Lambda Expressions in Java 8
java 8 new features
Lambda Expressions in Java 8

What's hot (20)

PPTX
Java 8 - Features Overview
PPTX
Functional programming with Java 8
PPTX
Java 8 presentation
PDF
Lambda Expressions in Java
PDF
Java 8 features
PDF
Java8 features
PPT
Major Java 8 features
PPTX
Java SE 8 - New Features
ODP
Introduction to Java 8
PDF
PDF
Functional programming with Java 8
PPTX
Actors model in gpars
PDF
Java 8 by example!
PDF
Java SE 8 library design
PDF
Functional programming in java 8 by harmeet singh
PPTX
Java 8 new features
PPTX
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
PPTX
New Features in JDK 8
PPTX
PPTX
10 Sets of Best Practices for Java 8
Java 8 - Features Overview
Functional programming with Java 8
Java 8 presentation
Lambda Expressions in Java
Java 8 features
Java8 features
Major Java 8 features
Java SE 8 - New Features
Introduction to Java 8
Functional programming with Java 8
Actors model in gpars
Java 8 by example!
Java SE 8 library design
Functional programming in java 8 by harmeet singh
Java 8 new features
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
New Features in JDK 8
10 Sets of Best Practices for Java 8
Ad

Viewers also liked (13)

PDF
Java 8 Lambda Expressions
PPTX
55 New Features in Java SE 8
PDF
Java 8 Lambda
PDF
Functional Programming in Java
PDF
Java 8 Workshop
PPT
Java 8 Streams
PDF
50 new things you can do with java 8
PDF
Java 8-streams-collectors-patterns
PDF
50 nouvelles choses que l'on peut faire avec Java 8
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
PDF
Les Streams sont parmi nous
PDF
Java 8 : Un ch'ti peu de lambda
PDF
Retours sur java 8 devoxx fr 2016
Java 8 Lambda Expressions
55 New Features in Java SE 8
Java 8 Lambda
Functional Programming in Java
Java 8 Workshop
Java 8 Streams
50 new things you can do with java 8
Java 8-streams-collectors-patterns
50 nouvelles choses que l'on peut faire avec Java 8
Java 8, Streams & Collectors, patterns, performances and parallelization
Les Streams sont parmi nous
Java 8 : Un ch'ti peu de lambda
Retours sur java 8 devoxx fr 2016
Ad

Similar to Introduction of Java 8 with emphasis on Lambda Expressions and Streams (20)

PDF
Java 8-revealed
PPTX
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
DOCX
Colloquium Report
PPTX
Java8: what's new and what's hot
PPTX
What’s new in java 8
PPTX
New Features of JAVA SE8
PDF
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
PPTX
Java 8 - An Overview
PDF
Java se 8 new features
PDF
Java SE 8 & EE 7 Launch
PPTX
Java 8 Features
PPTX
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
PPTX
Intro to java 8
PDF
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
PPTX
java150929145120-lva1-app6892 (2).pptx
PPT
14274730 (1).ppt
PPTX
What is new in Java 8
PPTX
java new technology
PPTX
Getting ready to java 8
PDF
JSR 335 / java 8 - update reference
Java 8-revealed
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Colloquium Report
Java8: what's new and what's hot
What’s new in java 8
New Features of JAVA SE8
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 - An Overview
Java se 8 new features
Java SE 8 & EE 7 Launch
Java 8 Features
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Intro to java 8
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
java150929145120-lva1-app6892 (2).pptx
14274730 (1).ppt
What is new in Java 8
java new technology
Getting ready to java 8
JSR 335 / java 8 - update reference

More from Emiel Paasschens (6)

PPTX
ACM Patterns and Oracle BPM Suite Best Practises
PPTX
Schematron
PPTX
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
PPTX
XML Business Rules Validation with Schematron
PPTX
Cookbook Oracle SOA Business Rules
PPTX
ACM Patterns and Oracle BPM Suite Best Practises
Schematron
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
XML Business Rules Validation with Schematron
Cookbook Oracle SOA Business Rules

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Electronic commerce courselecture one. Pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Mobile App Security Testing_ A Comprehensive Guide.pdf
sap open course for s4hana steps from ECC to s4
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
“AI and Expert System Decision Support & Business Intelligence Systems”
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation theory and applications.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectral efficient network and resource selection model in 5G networks
Digital-Transformation-Roadmap-for-Companies.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Electronic commerce courselecture one. Pdf
Spectroscopy.pptx food analysis technology
Per capita expenditure prediction using model stacking based on satellite ima...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11

Introduction of Java 8 with emphasis on Lambda Expressions and Streams

  • 1. Introduction Java 8 with emphasis on lambda expressions and streams Emiel Paasschens en Marcel Oldenkamp, 10 april 2014 Java SIG
  • 2. Agenda • What's new in Java 8 – Type annotations – Reflection – Compact profiles – New Date and Time API – Optional Class • Lambda expressies • Streams – Nashorn – Base64 – No More Permanent Generation – Default methods on interfaces – Static methods on interfaces
  • 3. 3 What's New in JDK 8 Type annotations • Type Annotations are annotations that can be placed anywhere you use a type. This includes the new operator, type casts, implements clauses and throws clauses. Type Annotations allow improved analysis of Java code and can ensure even stronger type checking. • Java 8 only provides the ability to define these types of annotations. It is then up to framework and tool developers to actually make use of it.
  • 4. 4 What's New in JDK 8 Method parameter reflection • Existing reflection methods – Get a reference to a Class – From the Class, get a reference to a Method by calling getDeclaredMethod() or getDeclaredMethods() which returns references to Method objects • New – From the Method object, call getParameters() which returns an array of Parameter objects – On the Parameter object, call getName() • Only works if code is compiled with -parameters compiler option
  • 5. 5 What's New in JDK 8 Compact profiles • Three Compact Profiles 1, 2, 3 – contain predefined subsets of the Java SE platform – reduced memory footprint, allows applications to run on resource-constrained devices (mobile, wearable such as glass, watch ) – compact profiles address API choices only; they are unrelated to the Java virtual machine (Jigsaw), the language, or tools.
  • 6. 6 What's New in JDK 8 New Date and Time API Java 8 introduces a new Date/Time API that is safer, easier to read, and more comprehensive than the previous API. Java‟s Calendar implementation has not changed much since it was first introduced and Joda-Time is widely regarded as a better replacement. Java 8‟s new Date/Time API is very similar to Joda-Time. For example, define the time 8 hours from now: Before Java 8: Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, 8); cal.getTime(); // actually returns a Date Java 8: LocalTime now = LocalTime.now(); LocalTime later = now.plus(8, HOURS);
  • 7. 7 What's New in JDK 8 Optional Class Java 8 comes with the Optional class in the java.util package for avoiding null return values (and thus NullPointerException). It is very similar to Google Guava‟s Optional and Scala‟s Option class. You can use Optional.of(x) to wrap a non-null value, Optional.empty() to represent a missing value, or Optional.ofNullable(x) to create an Optional from a reference that may or may not be null. After creating an instance of Optional, you then use isPresent() to determine if there is a value and get() to get the value. Optional provides a few other helpful methods for dealing with missing values: orElse(T) Returns the given default value if the Optional is empty. orElseGet(Supplier<T>) Calls on the given Supplier to provide a value if the Optional is empty. orElseThrow(Supplier<X extends Throwable>) Calls on the given Supplier for an exception to throw if the Optional is empty.
  • 8. 8 What's New in JDK 8 Nashorn Nashorn replaces Rhino as the default JavaScript engine for the Oracle JVM. Nashorn is much faster since it uses the invokedynamic feature of the JVM. It also includes a command line tool (jjs). You can run JavaScript files from the command line (java bin in your PATH): $ jjs script.js Running jjs with the -scripting option starts up an interactive shell: jjs> var date = new Date() jjs> print("${date}") You can also run JavaScript dynamically from Java: ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("nashorn"); engine.eval("function p(s) { print(s) }"); engine.eval("p('Hello Nashorn');"); engine.eval(new FileReader('library.js'));
  • 9. 9 What's New in JDK 8 Base64 Until now, Java developers have had to rely on third-party libraries for encoding and decoding Base-64. Since it is such a frequent operation, a large project will typically contain several different implementations of Base64. For example: Apache commons-codec, Spring, and Guava all have separate implementations. For this reason, Java 8 has java.util.Base64. It acts like a factory for Base64 encoders and decoders and has the following methods: getEncoder() getDecoder() getUrlEncoder() getUrlDecoder() The URL Base-64 Encoder provides an encoding that is URL and Filename safe.
  • 10. 10 What's New in JDK 8 No More Permanent Generation Most allocations for the class metadata are now allocated out of native memory. This means that you won‟t have to set the “XX:PermSize” options anymore (they don‟t exist). This also means that you will get a java.lang.OutOfMemoryError: Metadata space error message instead of java.lang.OutOfMemoryError: Permgen space when you run out of memory. This is part of the convergence of the Oracle JRockit and HotSpot JVMs. The proposed implementation will allocate class meta-data in native memory and move interned Strings and class statics to the Java heap. [http://openjdk.java.net/jeps/122]
  • 11. 11 What's New in JDK 8 Default methods on interfaces Default methods can be added to any interface. Like the name implies, any class that implements the interface but does not override the method will get the default implementation. interface Bar { default void talk() { System.out.println("Bar!"); } } class MyBar implements Bar { } MyBar myBar = new MyBar(); myBar.talk();
  • 12. 12 What's New in JDK 8 Default methods on interfaces With a multiple inherited default method, you have to implement! interface Foo { default void talk() { System.out.println("Foo!"); } } interface Bar { default void talk() { System.out.println("Bar!"); } } class FooBar implements Foo, Bar { @Override void talk() { Foo.super.talk(); } }
  • 13. 13 What's New in JDK 8 Static methods on interfaces The ability to add static methods to interfaces is a similar change to the Java language: This makes “helper” methods easier to find since they can be located directly on the interface, instead of a different class such as StreamUtil or Streams. Here‟s an example in the new Stream interface: public static<T> Stream<T> of(T... values) { return Arrays.stream(values); }
  • 14. 14 What's New in JDK 8 Others • JDK 8 includes Java DB 10.10 (Apache Derby open source database) • The Java SE 8 release contains Java API for XML Processing (JAXP) 1.6 • http://www.oracle.com/technetwork/java/javase/8-whats-new- 2157071.html
  • 15. 15 Lambda Expressions • Lambda Expressions – A new language feature. – Enable you to treat functionality as a method argument, or code as data. – Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.
  • 16. 16 Lambda Expressions • What is a Lambda Expression? – A lambda expression is an anonymous function. See it as a method without a declaration. (no access modifier, return value declaration, and name) – „functional expression treated as a variable‟ . – Ability to pass “functionality” as an argument, previous only possible using inner class.
  • 17. 17 Lambda Expressions • What is a Lambda Expression? – A lambda expression is an anonymous function. See it as a method without a declaration. (no access modifier, return value declaration, and name) – „functional expression treated as a variable‟ . – Ability to pass “functionality” as an argument, previous only possible using inner class. • Why do we need lambda expressions? – Convenience. Write a method in the same place you are going to use it. – In the „old days‟ Functions where not important for Java. On their own they cannot live in Java world. Lambda Expressions makes a Function a first class citizen, they exists on their own. – They make it easier to distribute processing of collections over multiple threads. • How do we define a lambda expression? – (Parameters) -> { Executed code }
  • 18. 18 Structure of Lambda Expressions • A lambda expression can have zero, one or more parameters. • The type of the parameters can be explicitly declared or it can be inferred from the context. is same as just • Parameters are enclosed in parentheses and separated by commas. • When there is a single parameter, parentheses are not mandatory • The body of the lambda expressions can contain zero, one or more statements. • If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression. • When there is more than one statement in body than these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned. or or
  • 19. 19 Functional Interface • Functional Interface is an interface with just one abstract method declared in it. (so the interface may have other default and static methods) • Indicated by the informative annotation @FunctionalInterface (the compiler will give an error if there are more abstract methods) • java.lang.Runnable is an example of a Functional Interface. There is only one method void run(). • Other examples are Comparator and ActionListener.
  • 20. 20 Functional Interface – „the old way‟ • Functional Interface is an interface with just one abstract method declared in it. • Example of assigning „on the fly‟ functionality (the old way)
  • 21. 21 Functional Interface example Runnable using Lambda NEW: • Example of assigning „on the fly‟ functionality (the new way) • A lambda expression evaluates to an instance of a functional interface OLD:
  • 22. 22 Functional Interface example Runnable using Lambda Even shorter notation:
  • 23. 23 Functional Interface example ActionListener using Lambda NEW: Example of a lambda expression with parameters (functional interface actionlistener) OLD:
  • 25. 25 Predefined Functional Interfaces Java 8 comes with several functional interfaces in package java.util.function: • Function<T,R> Takes an object of type T and returns R. • Supplier<T> Just returns an object of type T. • Predicate<T> Returns a boolean value based on input of type T. • Consumer<T> Performs an action with given object of type T. • BiFunction Like Function but with two parameters. • BiConsumer Like Consumer but with two parameters. It also comes with several corresponding interfaces for primitive types, e.g: • IntFunction<R> • IntSupplier • IntPredicate • IntConsumer
  • 26. 26 Method References Since a lambda expression is like a method without an object attached, wouldn‟t it be nice if we could refer to existing methods instead of using a lamda expression? This is exactly what we can do with method references: public class FileFilters { public static boolean fileIsPdf(File file) {/*code*/} public static boolean fileIsTxt(File file) {/*code*/} public static boolean fileIsRtf(File file) {/*code*/} } List<File> files = new LinkedList<>(getFiles()); files.stream().filter(FileFilters::fileIsRtf) .forEach(System.out::println);
  • 27. 27 Method References Method references can point to: • Static methods (ie. previous slide). • Instance methods (ie. 2 below). • Methods on particular instances (ie. line 4 below). • Constructors (ie. TreeSet::new) For example, using the new java.nio.file.Files.lines method: 1 Files.lines(Paths.get("Nio.java")) 2 .map(String::trim) 3 .filter(s -> !s.isEmpty()) 4 .forEach(System.out::println);
  • 28. 28 Collections - Streams • In Java <= 7 collections can only be manipulated through iterators • Verbose way of saying: – "the sum of the weights of the red blocks in a collection of blocks“ • Programmer expresses how the computer should execute an algorithm • But, programmer is usually only interested in what the computer should calculate • To this end, other languages already provide what is sometimes called a pipes-and- filters-based API for collections. – Like linux: cat diagnostic.log | grep error | more
  • 29. 29 Collections - Streams • Java is extended with a similar API for its collections using filter and map, which take as argument a (lambda) expression. • Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements. • The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations.
  • 30. 30 Collections - Streams Stream can be used only once! Stream consists of: 1. One source 2. Zero or more intermediate operations (e.g. filter, map) 3. One terminal operation (forEach, reduce, sum)
  • 31. 31 Collections - Streams Some examples of sources: • From a Collection via the stream() and parallelStream() methods; • From an array via Arrays.stream(Object[]); • From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator); • The lines of a file can be obtained from BufferedReader.lines(); • Streams of file paths can be obtained from methods in Files; • Streams of random numbers can be obtained from Random.ints(); • Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream().
  • 32. 32 Collections - Streams Intermediate operations: • distinct() Remove all duplicate elements using equals method • filter(Predicate<T> predicate) Filters elements using predicate • limit(long maxSize) Truncates stream to first elements till maxSize (can be slow when parallel processing on ordered parallel pipelines) • map(Function<T,R> mapper) Map/convert object to other object • peek(Consumer<T> action) Apply given method on each element tip: useful for debugging: .peek(o -> System.out.println("o: " + o)) • skip(long n) Remove first n element from Stream (can be slow when parallel processing on ordered parallel pipelines) • sorted(Comparator<T> comparator) Sort the stream with given Comparator
  • 33. 33 Collections - Streams Terminal operations: • boolean allMatch,anyMatch,noneMatch(Predicate<T> predicate) • long count() The count of all elements. • Optional<T> findAny() Return any element (or empty Optional) • Optional<T> findFirst() Return 1st element (or empty Optional) • Optional<T> min,max(Comparator<T> comparator) Return first or last element according to comparator • void forEach(Consumer<T> action) Performs action on each element • T reduce(T identity, BinaryOperator<T> accumulator)‟Combine‟ all elements T to one final result T. Sum, min, max, average, and string concatenation are all special cases of reduction, e.g. Integer sum = integers.reduce(0, (a, b) -> a+b); PS The methods sum() and average() are available on „specialized‟ Streams IntStream, LongStream and DoubleStream
  • 34. 34 Collections - Streams Terminal operations: • collect(Supplier<R> supplier, BiConsumer<R,T> accumulator, BiConsumer<R,R> combiner) Performs operation accumulator on all elements of type T resulting into result R. class Averager implements IntConsumer { private int total = 0; private int count = 0; public double average() { return count > 0 ? ((double) total)/count : 0; } public void accept(int i) { total += i; count++; } public void combine(Averager other) { total += other.total; count += other.count; } } ages.collect(Averager::new, Averager::accept, Averager::combine);
  • 35. 35 More information More info AMIS Blog: • http://technology.amis.nl/2013/10/03/java-8-the-road-to-lambda-expressions/ • http://technology.amis.nl/2013/10/05/java-8-collection-enhancements-leveraging-lambda- expressions-or-how-java-emulates-sql/ Others: • https://leanpub.com/whatsnewinjava8/read#leanpub-auto-default-methods • http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html • http://java.dzone.com/articles/why-we-need-lambda-expressions • http://viralpatel.net/blogs/lambda-expressions-java-tutorial/ • http://www.angelikalanger.com/Lambdas/Lambdas.html • http://www.coreservlets.com/java-8-tutorial/#streams-2 • http://java.dzone.com/articles/interface-default-methods-java
  • 36. 36

Editor's Notes

  • #4: http://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.htmlhttp://java.dzone.com/articles/java-8-type-annotations
  • #5: http://stackoverflow.com/questions/21455403/how-to-get-method-parameter-names-in-java-8-using-reflection
  • #6: http://docs.oracle.com/javase/8/docs/technotes/guides/compactprofiles/compactprofiles.htmlhttp://vitalflux.com/why-when-use-java-8-compact-profiles/
  • #7: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #8: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #9: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #10: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #11: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #12: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #13: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #14: https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  • #15: http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
  • #17: http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
  • #18: http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
  • #20: http://www.stoyanr.com/2012/12/devoxx-2012-java-8-lambda-and.html
  • #21: http://www.stoyanr.com/2012/12/devoxx-2012-java-8-lambda-and.html
  • #29: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  • #30: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  • #31: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  • #32: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  • #33: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  • #34: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  • #35: http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html