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
Ad

More Related Content

What's hot (20)

Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Java8 features
Java8 featuresJava8 features
Java8 features
Elias Hasnat
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Java8
Java8Java8
Java8
Felipe Mamud
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
NexThoughts Technologies
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
Mark Harrison
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
Stephen Colebourne
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Harmeet Singh(Taara)
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Java 8
Java 8Java 8
Java 8
Sudipta K Paik
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
Garth Gilmour
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
Talha Ocakçı
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
Harmeet Singh(Taara)
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Harmeet Singh(Taara)
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
Garth Gilmour
 

Viewers also liked (13)

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
Simon Ritter
 
Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
François Sarradin
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
Premanand Chandrasekaran
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
José Paumard
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
50 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 850 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 8
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
José Paumard
 
Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambda
Ch'ti JUG
 
Retours sur java 8 devoxx fr 2016
Retours sur java 8 devoxx fr 2016Retours sur java 8 devoxx fr 2016
Retours sur java 8 devoxx fr 2016
Jean-Michel Doudoux
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
Simon Ritter
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
José Paumard
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
50 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 850 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 8
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
José Paumard
 
Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambda
Ch'ti JUG
 
Retours sur java 8 devoxx fr 2016
Retours sur java 8 devoxx fr 2016Retours sur java 8 devoxx fr 2016
Retours sur java 8 devoxx fr 2016
Jean-Michel Doudoux
 
Ad

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

Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
Mohammad Faizan
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
Nicola Pedot
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Nayden Gochev
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
Dinesh Pathak
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
Tobias Coetzee
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
Syed Awais Mazhar Bukhari
 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
Ken Coenen
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
Digicomp Academy AG
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
aptechaligarh
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solution
Mazenetsolution
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev
 
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Java Interview Questions for 10+ Year Experienced PDF By ScholarHatJava Interview Questions for 10+ Year Experienced PDF By ScholarHat
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Scholarhat
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
Bansilal Haudakari
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
FFM / Panama: A case study with OpenSSL and Tomcat
FFM / Panama: A case study with OpenSSL and TomcatFFM / Panama: A case study with OpenSSL and Tomcat
FFM / Panama: A case study with OpenSSL and Tomcat
Jean-Frederic Clere
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
Dori Waldman
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
Hamed Hatami
 
Java basic
Java basicJava basic
Java basic
Arati Gadgil
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Nayden Gochev
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdfJava 8 Interview Questions and Answers PDF By ScholarHat.pdf
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
Dinesh Pathak
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solution
Mazenetsolution
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
Nayden Gochev
 
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Java Interview Questions for 10+ Year Experienced PDF By ScholarHatJava Interview Questions for 10+ Year Experienced PDF By ScholarHat
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Scholarhat
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
Bansilal Haudakari
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
Ahmed mar3y
 
FFM / Panama: A case study with OpenSSL and Tomcat
FFM / Panama: A case study with OpenSSL and TomcatFFM / Panama: A case study with OpenSSL and Tomcat
FFM / Panama: A case study with OpenSSL and Tomcat
Jean-Frederic Clere
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
Dori Waldman
 
Ad

More from Emiel Paasschens (6)

ACM Patterns and Oracle BPM Suite Best Practises
ACM Patterns and Oracle BPM Suite Best PractisesACM Patterns and Oracle BPM Suite Best Practises
ACM Patterns and Oracle BPM Suite Best Practises
Emiel Paasschens
 
Schematron
SchematronSchematron
Schematron
Emiel Paasschens
 
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business valueBoost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
Emiel Paasschens
 
XML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronXML Business Rules Validation with Schematron
XML Business Rules Validation with Schematron
Emiel Paasschens
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business Rules
Emiel Paasschens
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
Emiel Paasschens
 
ACM Patterns and Oracle BPM Suite Best Practises
ACM Patterns and Oracle BPM Suite Best PractisesACM Patterns and Oracle BPM Suite Best Practises
ACM Patterns and Oracle BPM Suite Best Practises
Emiel Paasschens
 
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business valueBoost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
Boost JD Edwards EnterpriseOne with Oracle SOA Suite for maximum business value
Emiel Paasschens
 
XML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronXML Business Rules Validation with Schematron
XML Business Rules Validation with Schematron
Emiel Paasschens
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business Rules
Emiel Paasschens
 

Recently uploaded (20)

Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 

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