SlideShare a Scribd company logo
1 of 36
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

Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New FeaturesNaveen Hegde
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha 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 singhHarmeet 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 8Martin 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 8Garth Gilmour
 

What's hot (20)

Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java8
Java8Java8
Java8
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Java SE 8 library design
Java SE 8 library designJava SE 8 library design
Java SE 8 library design
 
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
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
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)
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java 8
Java 8Java 8
Java 8
 
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
 

Viewers also liked

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 8Simon 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 8José Paumard
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJosé 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 8José 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 parallelizationJosé Paumard
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nousJosé 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 lambdaCh'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 2016Jean-Michel Doudoux
 

Viewers also liked (13)

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
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
 
Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
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
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
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
 
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
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
 
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
 
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
 

Similar to Introduction to Java 8 Lambda Expressions and Streams

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
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8Dinesh Pathak
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionMazenetsolution
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014Nayden Gochev
 
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 itiAhmed mar3y
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8 Dori Waldman
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressionsLars Lemos
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterSimon Ritter
 

Similar to Introduction to Java 8 Lambda Expressions and Streams (20)

Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
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
 
New Features of JAVA SE8
New Features of JAVA SE8New Features of JAVA SE8
New Features of JAVA SE8
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
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
 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
 
14274730 (1).ppt
14274730 (1).ppt14274730 (1).ppt
14274730 (1).ppt
 
Java- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solutionJava- Updates in java8-Mazenet solution
Java- Updates in java8-Mazenet solution
 
Software Uni Conf October 2014
Software Uni Conf October 2014Software Uni Conf October 2014
Software Uni Conf October 2014
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
whats new in java 8
whats new in java 8 whats new in java 8
whats new in java 8
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Java basic
Java basicJava basic
Java basic
 
Java 8 lambdas expressions
Java 8 lambdas expressionsJava 8 lambdas expressions
Java 8 lambdas expressions
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
Java 7 & 8 - A&BP CC
Java 7 & 8 - A&BP CCJava 7 & 8 - A&BP CC
Java 7 & 8 - A&BP CC
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritter
 

More from 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 PractisesEmiel 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 valueEmiel Paasschens
 
XML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronXML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronEmiel Paasschens
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesEmiel Paasschens
 

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
 
Schematron
SchematronSchematron
Schematron
 
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
 
XML Business Rules Validation with Schematron
XML Business Rules Validation with SchematronXML Business Rules Validation with Schematron
XML Business Rules Validation with Schematron
 
Cookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business RulesCookbook Oracle SOA Business Rules
Cookbook Oracle SOA Business Rules
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Introduction to Java 8 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

  1. http://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.htmlhttp://java.dzone.com/articles/java-8-type-annotations
  2. http://stackoverflow.com/questions/21455403/how-to-get-method-parameter-names-in-java-8-using-reflection
  3. http://docs.oracle.com/javase/8/docs/technotes/guides/compactprofiles/compactprofiles.htmlhttp://vitalflux.com/why-when-use-java-8-compact-profiles/
  4. https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  5. https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  6. https://leanpub.com/whatsnewinjava8/read#leanpub-auto-no-more-permanent-generation
  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. http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
  13. http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
  14. http://viralpatel.net/blogs/lambda-expressions-java-tutorial/
  15. http://www.stoyanr.com/2012/12/devoxx-2012-java-8-lambda-and.html
  16. http://www.stoyanr.com/2012/12/devoxx-2012-java-8-lambda-and.html
  17. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  18. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  19. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  20. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  21. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  22. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html
  23. http://blog.hartveld.com/2013/03/jdk-8-33-stream-api.html