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

What's hot (20)

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

Viewers also liked (13)

PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PPTX
55 New Features in Java SE 8
Simon Ritter
 
PDF
Java 8 Lambda
François Sarradin
 
PDF
Functional Programming in Java
Premanand Chandrasekaran
 
PDF
Java 8 Workshop
Mario Fusco
 
PPT
Java 8 Streams
Manvendra Singh
 
PDF
50 new things you can do with java 8
José Paumard
 
PDF
Java 8-streams-collectors-patterns
José Paumard
 
PDF
50 nouvelles choses que l'on peut faire avec Java 8
José Paumard
 
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
PDF
Les Streams sont parmi nous
José Paumard
 
PDF
Java 8 : Un ch'ti peu de lambda
Ch'ti JUG
 
PDF
Retours sur java 8 devoxx fr 2016
Jean-Michel Doudoux
 
Java 8 Lambda Expressions
Scott Leberknight
 
55 New Features in Java SE 8
Simon Ritter
 
Java 8 Lambda
François Sarradin
 
Functional Programming in Java
Premanand Chandrasekaran
 
Java 8 Workshop
Mario Fusco
 
Java 8 Streams
Manvendra Singh
 
50 new things you can do with java 8
José Paumard
 
Java 8-streams-collectors-patterns
José Paumard
 
50 nouvelles choses que l'on peut faire avec Java 8
José Paumard
 
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Les Streams sont parmi nous
José Paumard
 
Java 8 : Un ch'ti peu de lambda
Ch'ti JUG
 
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)

PDF
Java 8-revealed
Hamed Hatami
 
PPTX
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Srimanta Sahu
 
DOCX
Colloquium Report
Mohammad Faizan
 
PPTX
Java8: what's new and what's hot
Sergii Maliarov
 
PPTX
What’s new in java 8
Rajmahendra Hegde
 
PPTX
New Features of JAVA SE8
Dinesh Pathak
 
PDF
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
PPTX
Java 8 - An Overview
Indrajit Das
 
PDF
Java se 8 new features
Aymen Masri
 
PDF
Java SE 8 & EE 7 Launch
Digicomp Academy AG
 
PPTX
Java 8 Features
Trung Nguyen
 
PPTX
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Olena Syrota
 
PPTX
Intro to java 8
John Godoi
 
PDF
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
Getting value from IoT, Integration and Data Analytics
 
PPTX
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
PPT
14274730 (1).ppt
aptechaligarh
 
PPTX
What is new in Java 8
Sandeep Kr. Singh
 
PPTX
java new technology
chavdagirimal
 
PPTX
Getting ready to java 8
Strannik_2013
 
PDF
JSR 335 / java 8 - update reference
sandeepji_choudhary
 
Java 8-revealed
Hamed Hatami
 
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Srimanta Sahu
 
Colloquium Report
Mohammad Faizan
 
Java8: what's new and what's hot
Sergii Maliarov
 
What’s new in java 8
Rajmahendra Hegde
 
New Features of JAVA SE8
Dinesh Pathak
 
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
Scholarhat
 
Java 8 - An Overview
Indrajit Das
 
Java se 8 new features
Aymen Masri
 
Java SE 8 & EE 7 Launch
Digicomp Academy AG
 
Java 8 Features
Trung Nguyen
 
Java World, Java Trends, Java 8 and Beyond (iForum - 2014)
Olena Syrota
 
Intro to java 8
John Godoi
 
AMIS Oracle OpenWorld 2013 Review Part 3 - Fusion Middleware
Getting value from IoT, Integration and Data Analytics
 
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
14274730 (1).ppt
aptechaligarh
 
What is new in Java 8
Sandeep Kr. Singh
 
java new technology
chavdagirimal
 
Getting ready to java 8
Strannik_2013
 
JSR 335 / java 8 - update reference
sandeepji_choudhary
 
Ad

More from Emiel Paasschens (6)

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

Recently uploaded (20)

PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 

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