SlideShare a Scribd company logo
Java8 Stream API
A different way to process collections
David Gómez G.
@dgomezg
dgomezg@autentia.com
Streams?
What’s that?
A Stream is…
An convenience method to iterate over
collections in a declarative way
List<Integer>  numbers  =  new  ArrayList<Integer>();

for  (int  i=  0;  i  <  100  ;  i++)  {

   numbers.add(i);

}  
List<Integer> evenNumbers = new ArrayList<>();

for (int i : numbers) {

if (i % 2 == 0) {

evenNumbers.add(i);

}

}
@dgomezg
A Stream is…
An convenience method to iterate over
collections in a declarative way
List<Integer>  numbers  =  new  ArrayList<Integer>();

for  (int  i=  0;  i  <  100  ;  i++)  {

   numbers.add(i);

}  
List<Integer> evenNumbers = numbers.stream()

.filter(n -> n % 2 == 0)

.collect(toList());
@dgomezg
So… Streams are collections?
Not Really
Collections Streams
Sequence of elements
Computed at construction
In-memory data structure
Sequence of elements
Computed at iteration
Traversable only Once
External Iteration Internal Iteration
Finite size Infinite size
@dgomezg
Iterating a Collection
List<Integer> evenNumbers = new ArrayList<>();

for (int i : numbers) {

if (i % 2 == 0) {

evenNumbers.add(i);

}

}
External Iteration
- Use forEach or Iterator
- Very verbose
Parallelism by manually using Threads
- Concurrency is hard to be done right!
- Lots of contention and error-prone
- Thread-safety@dgomezg
Iterating a Stream
List<Integer> evenNumbers = numbers.stream()

.filter(n -> n % 2 == 0)

.collect(toList());
Internal Iteration
- No manual Iterators handling
- Concise
- Fluent API: chain sequence processing
Elements computed only when needed
@dgomezg
Iterating a Stream
List<Integer> evenNumbers = numbers.parallelStream()

.filter(n -> n % 2 == 0)

.collect(toList());
Easily Parallelism
- Concurrency is hard to be done right!
- Uses ForkJoin
- Process steps should be
- stateless
- independent
@dgomezg
Lambdas
&
Method References
@FunctionalInterface
@FunctionalInterface

public interface Predicate<T> {


boolean test(T t);
!
!
!
!
!
}
An interface with exactly one abstract method
!
!
@dgomezg
@FunctionalInterface
@FunctionalInterface

public interface Predicate<T> {


boolean test(T t);
!
default Predicate<T> negate() {

return (t) -> !test(t);

}


!
}
An interface with exactly one abstract method
Could have default methods, though!
!
@dgomezg
Lambda Types
Based on abstract method signature from
@FunctionalInterface:
(Arguments) -> <return type>
@FunctionalInterface

public interface Predicate<T> {


boolean test(T t);
}
T -> boolean
@dgomezg
Lambda Types
Based on abstract method signature from
@FunctionalInterface:
(Arguments) -> <return type>
@FunctionalInterface

public interface Runnable {


void run();
}
() -> void
@dgomezg
Lambda Types
Based on abstract method signature from
@FunctionalInterface:
(Arguments) -> <return type>
@FunctionalInterface

public interface Supplier<T> {


T get();
}
() -> T
@dgomezg
Lambda Types
Based on abstract method signature from
@FunctionalInterface:
(Arguments) -> <return type>
@FunctionalInterface

public interface BiFunction<T, U, R> {


R apply(T t, U t);
}
(T, U) -> R
@dgomezg
Lambda Types
Based on abstract method signature from
@FunctionalInterface:
(Arguments) -> <return type>
@FunctionalInterface

public interface Comparator<T> {


int compare(T o1, T o2);
}
(T, T) -> int
@dgomezg
Method References
Allows to use a method name as a lambda
Usually better readability
!
Syntax:
<TargetReference>::<MethodName>
!
TargetReference: Instance or Class
@dgomezg
Method References
phoneCall -> phoneCall.getContact()
Method ReferenceLambda
PhoneCall::getContact
() -> Thread.currentThread() Thread::currentThread
(str, c) -> str.indexOf(c) String::indexOf
(String s) -> System.out.println(s) System.out::println
@dgomezg
From Collections
to
Streams
Characteristics of A Stream
• Interface to Sequence of elements
• Focused on processing (not on storage)
• Elements computed on demand
(or extracted from source)
• Can be traversed only once
• Internal iteration
• Parallel Support
• Could be Infinite
@dgomezg
Anatomy of a Stream
Source
Intermediate
Operations
filter
map
order
function
Final
operation
pipeline
@dgomezg
Anatomy of Stream Iteration
1. Start from the DataSource (Usually a
collection) and create the Stream
List<Integer> numbers =
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);


Stream<Integer> numbersStream = numbers.stream();

@dgomezg
Anatomy of Stream Iteration
2. Add a chain of intermediate Operations
(Stream Pipeline)
Stream<Integer> numbersStream = numbers.stream()

.filter(new Predicate<Integer>() {

@Override

public boolean test(Integer number) {

return number % 2 == 0;

}

})
!
.map(new Function<Integer, Integer>() {

@Override

public Integer apply(Integer number) {

return number * 2;

}

});
@dgomezg
Anatomy of Stream Iteration
2. Add a chain of intermediate Operations
(Stream Pipeline) - Better using lambdas
Stream<Integer> numbersStream = numbers.stream()

.filter(number -> number % 2 == 0)

.map(number -> number * 2);
@dgomezg
Anatomy of Stream Iteration
3. Close with a Terminal Operation
List<Integer> numbersStream = numbers.stream()

.filter(number -> number % 2 == 0)

.map(number -> number * 2)
.collect(Collectors.toList());
•The terminal operation triggers Stream Iteration
•Before that, nothing is computed.
•Depending on the terminal operation, the
stream could be fully traversed or not.
@dgomezg
Stream operations
Operation Types
Intermediate operations
• Always return a Stream
• Chain as many as needed (Pipeline)
• Guide processing of data
• Does not start processing
• Can be Stateless or Stateful
Terminal operations
• Can return an object, a collection, or void
• Start the pipeline process
• After its execution, the Stream can not be
revisited
Intermediate Operations
// T -> boolean
Stream<T> filter(Predicate<? super T> predicate);
!
//T -> R

<R> Stream<R> map(Function<? super T, ? extends R> mapper);


//(T,T) -> int

Stream<T> sorted(Comparator<? super T> comparator);
Stream<T> sorted();
!
//T -> void

Stream<T> peek(Consumer<? super T> action);
!
Stream<T> distinct();

Stream<T> limit(long maxSize);

Stream<T> skip(long n);
@dgomezg
Final Operations
Object[] toArray();
void forEach(Consumer<? super T> action); //T -> void

<R, A> R collect(Collector<? super T, A, R> collector);

!
!
java.util.stream.Collectors.toList();
java.util.stream.Collectors.toSet();
java.util.stream.Collectors.toMap();
java.util.stream.Collectors.joining(CharSequence);
!
!
!
@dgomezg
Final Operations (II)
//T,U -> R
Optional<T> reduce(BinaryOperator<T> accumulator);
//(T,T) -> int

Optional<T> min(Comparator<? super T> comparator);

//(T,T) -> int
Optional<T> max(Comparator<? super T> comparator);

long count();

!
@dgomezg
Final Operations (y III)
//T -> boolean
boolean anyMatch(Predicate<? super T> predicate);

boolean allMatch(Predicate<? super T> predicate);

boolean noneMatch(Predicate<? super T> predicate);

!
@dgomezg
Usage examples - Context
public class Contact {

private final String name;

private final String city;

private final String phoneNumber;

private final LocalDate birth;





public int getAge() {

return Period.between(birth, LocalDate.now())

.getYears();

}

//Constructor and getters omitted

!
}

@dgomezg
Usage examples - Context
public class PhoneCall {

private final Contact contact;

private final LocalDate time;

private final Duration duration;

!
//Constructor and getters omitted
}

Contact me = new Contact("dgomezg", "Madrid", "555 55 55 55", LocalDate.of(1975, Month.MARCH, 26));

Contact martin = new Contact("Martin", "Santiago", "666 66 66 66", LocalDate.of(1978, Month.JANUARY, 17));

Contact roberto = new Contact("Roberto", "Santiago", "111 11 11 11", LocalDate.of(1973, Month.MAY, 11));

Contact heinz = new Contact("Heinz", "Chania", "444 44 44 44", LocalDate.of(1972, Month.APRIL, 29));

Contact michael = new Contact("michael", "Munich", "222 22 22 22", LocalDate.of(1976, Month.DECEMBER, 8));



List<PhoneCall> phoneCallLog = Arrays.asList(

new PhoneCall(heinz, LocalDate.of(2014, Month.MAY, 28), Duration.ofSeconds(125)),

new PhoneCall(martin, LocalDate.of(2014, Month.MAY, 30), Duration.ofMinutes(5)),

new PhoneCall(roberto, LocalDate.of(2014, Month.MAY, 30), Duration.ofMinutes(12)),

new PhoneCall(michael, LocalDate.of(2014, Month.MAY, 28), Duration.ofMinutes(3)),

new PhoneCall(michael, LocalDate.of(2014, Month.MAY, 29), Duration.ofSeconds(90)),

new PhoneCall(heinz, LocalDate.of(2014, Month.MAY, 30), Duration.ofSeconds(365)),

new PhoneCall(heinz, LocalDate.of(2014, Month.JUNE, 1), Duration.ofMinutes(7)),

new PhoneCall(martin, LocalDate.of(2014, Month.JUNE, 2), Duration.ofSeconds(315))

) ;
@dgomezg
People I phoned in June
phoneCallLog.stream()

.filter(phoneCall ->
phoneCall.getTime().getMonth() == Month.JUNE)

.map(phoneCall -> phoneCall.getContact().getName())

.distinct()

.forEach(System.out::println);

!
@dgomezg
Seconds I talked in May
Long total = phoneCallLog.stream()

.filter(phoneCall ->
phoneCall.getTime().getMonth() == Month.MAY)

.map(PhoneCall::getDuration)

.collect(summingLong(Duration::getSeconds));
@dgomezg
Seconds I talked in May
Optional<Long> total = phoneCallLog.stream()

.filter(phoneCall ->
phoneCall.getTime().getMonth() == Month.MAY)

.map(PhoneCall::getDuration)

.reduce(Duration::plus);


total.ifPresent(duration ->
{System.out.println(duration.getSeconds());}
);

!
@dgomezg
Did I phone to Paris?
boolean phonedToParis = phoneCallLog.stream()

.anyMatch(phoneCall ->
"Paris".equals(phoneCall.getContact().getCity()))

!
!
@dgomezg
Give me the 3 longest phone calls
phoneCallLog.stream()

.filter(phoneCall ->
phoneCall.getTime().getMonth() == Month.MAY)

.sorted(comparing(PhoneCall::getDuration))

.limit(3)

.forEach(System.out::println);
@dgomezg
Give me the 3 shortest ones
phoneCallLog.stream()

.filter(phoneCall ->
phoneCall.getTime().getMonth() == Month.MAY)

.sorted(comparing(PhoneCall::getDuration).reversed())

.limit(3)

.forEach(System.out::println);
@dgomezg
Creating Streams
Streams can be created from
Collections
Directly from values
Generators (infinite Streams)
Resources (like files)
Stream ranges
@dgomezg
From collections
use stream()
List<Integer> numbers = new ArrayList<>();

for (int i= 0; i < 10_000_000 ; i++) {

numbers.add((int)Math.round(Math.random()*100));

}
Stream<Integer> evenNumbers = numbers.stream();
or parallelStream()
Stream<Integer> evenNumbers = numbers.parallelStream();
@dgomezg
Directly from Values & ranges
Stream.of("Using", "Stream", "API", "From", “Java8”);
can convert into parallelStream
Stream.of("Using", "Stream", "API", "From", “Java8”)
.parallel();

@dgomezg
Generators - Functions
Stream<Integer> integers =
Stream.iterate(0, number -> number + 2);
This is an infinite Stream!,
will never be exhausted!
Stream fibonacci =
Stream.iterate(new int[]{0,1},
t -> new int[]{t[1],t[0]+t[1]});


fibonacci.limit(10)

.map(t -> t[0])

.forEach(System.out::println);
@dgomezg
Generators - Functions
Stream<Integer> integers =
Stream.iterate(0, number -> number + 2);
This is an infinite Stream!,
will never be exhausted!
Stream fibonacci =
Stream.iterate(new int[]{0,1},
t -> new int[]{t[1],t[0]+t[1]});


fibonacci.limit(10)

.map(t -> t[0])

.forEach(System.out::println);
@dgomezg
From Resources (Files)
Stream<String> fileContent =
Files.lines(Paths.get(“readme.txt”));
Files.lines(Paths.get(“readme.txt”))

.flatMap(line -> Arrays.stream(line.split(" ")))

.distinct()

.count());

!
Count all distinct words in a file
@dgomezg
Parallelism
Parallel Streams
use stream()
List<Integer> numbers = new ArrayList<>();

for (int i= 0; i < 10_000_000 ; i++) {

numbers.add((int)Math.round(Math.random()*100));

}
//This will use just a single thread
Stream<Integer> evenNumbers = numbers.stream();
or parallelStream()
//Automatically select the optimum number of threads
Stream<Integer> evenNumbers = numbers.parallelStream();
@dgomezg
Let’s test it
use stream()
!
for (int i = 0; i < 100; i++) {

long start = System.currentTimeMillis();

List<Integer> even = numbers.stream()

.filter(n -> n % 2 == 0)

.sorted()

.collect(toList());


System.out.printf(
"%d elements computed in %5d msecs with %d threadsn”,

even.size(), System.currentTimeMillis() - start,
Thread.activeCount());

}
5001983 elements computed in 828 msecs with 2 threads
5001983 elements computed in 843 msecs with 2 threads
5001983 elements computed in 675 msecs with 2 threads
5001983 elements computed in 795 msecs with 2 threads
@dgomezg
Let’s test it
use stream()
!
for (int i = 0; i < 100; i++) {

long start = System.currentTimeMillis();

List<Integer> even = numbers.parallelStream()

.filter(n -> n % 2 == 0)

.sorted()

.collect(toList());


System.out.printf(
"%d elements computed in %5d msecs with %d threadsn”,

even.size(), System.currentTimeMillis() - start,
Thread.activeCount());

}
4999299 elements computed in 225 msecs with 9 threads
4999299 elements computed in 230 msecs with 9 threads
4999299 elements computed in 250 msecs with 9 threads
@dgomezg
Enough, for now,
But this is just the beginning
Thank You.
@dgomezg
dgomezg@gmail.com
www.adictosaltrabajlo.com

More Related Content

What's hot

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
NexThoughts Technologies
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
Xcat Liu
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
SameerAhmed593310
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
jQuery
jQueryjQuery
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 

What's hot (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
07 java collection
07 java collection07 java collection
07 java collection
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
jQuery
jQueryjQuery
jQuery
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 

Viewers also liked

Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
Heartin Jacob
 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introduction
Stephen Colebourne
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeJava 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Nikita Lipsky
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
Mohammad Hossein Rimaz
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
David Gómez García
 
The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)
Robert Scholte
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
Trisha Gee
 

Viewers also liked (9)

Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Java SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introductionJava SE 9 modules (JPMS) - an introduction
Java SE 9 modules (JPMS) - an introduction
 
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeJava 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
 
Java 9, JShell, and Modularity
Java 9, JShell, and ModularityJava 9, JShell, and Modularity
Java 9, JShell, and Modularity
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)The do's and don'ts with java 9 (Devoxx 2017)
The do's and don'ts with java 9 (Devoxx 2017)
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
 

Similar to Java 8 Stream API. A different way to process collections.

C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Codemotion
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
Chapter 2
Chapter 2Chapter 2
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
Esther Lozano
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
Peter Lawrey
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
franciscoortin
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematicakrasul
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within MathematicaShoaib Burq
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyasrsnarayanan
 
The STL
The STLThe STL
The STL
adil raja
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 

Similar to Java 8 Stream API. A different way to process collections. (20)

C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematica
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within Mathematica
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
 
The STL
The STLThe STL
The STL
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 

More from David Gómez García

Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022
David Gómez García
 
Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...
David Gómez García
 
Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...
David Gómez García
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
David Gómez García
 
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
David Gómez García
 
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationCdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
David Gómez García
 
What's in a community like Liferay's
What's in a community like Liferay'sWhat's in a community like Liferay's
What's in a community like Liferay's
David Gómez García
 
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
David Gómez García
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
David Gómez García
 
Construccion de proyectos con gradle
Construccion de proyectos con gradleConstruccion de proyectos con gradle
Construccion de proyectos con gradle
David Gómez García
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)David Gómez García
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min.
David Gómez García
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
David Gómez García
 
El poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaEl poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesanía
David Gómez García
 
Geo-SentimentZ
Geo-SentimentZGeo-SentimentZ
Geo-SentimentZ
David Gómez García
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript Scripting
David Gómez García
 
A real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbA real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodb
David Gómez García
 
Spring Data y Mongo DB en un proyecto Real
Spring Data y Mongo DB en un proyecto RealSpring Data y Mongo DB en un proyecto Real
Spring Data y Mongo DB en un proyecto Real
David Gómez García
 

More from David Gómez García (20)

Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022Leverage CompletableFutures to handle async queries. DevNexus 2022
Leverage CompletableFutures to handle async queries. DevNexus 2022
 
Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...Building Modular monliths that could scale to microservices (only if they nee...
Building Modular monliths that could scale to microservices (only if they nee...
 
Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...Building modular monoliths that could scale to microservices (only if they ne...
Building modular monoliths that could scale to microservices (only if they ne...
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
Builiding Modular monoliths that can scale to microservices. JBCNConf 2021
 
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integrationCdm mil-18 - hypermedia ap is for headless platforms and data integration
Cdm mil-18 - hypermedia ap is for headless platforms and data integration
 
What's in a community like Liferay's
What's in a community like Liferay'sWhat's in a community like Liferay's
What's in a community like Liferay's
 
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Construccion de proyectos con gradle
Construccion de proyectos con gradleConstruccion de proyectos con gradle
Construccion de proyectos con gradle
 
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
Midiendo la calidad de código en WTF/Min (Revisado EUI Abril 2014)
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min.
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
Gradle como alternativa a maven
Gradle como alternativa a mavenGradle como alternativa a maven
Gradle como alternativa a maven
 
El poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesaníaEl poder del creador de Software. Entre la ingeniería y la artesanía
El poder del creador de Software. Entre la ingeniería y la artesanía
 
Geo-SentimentZ
Geo-SentimentZGeo-SentimentZ
Geo-SentimentZ
 
HDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript ScriptingHDTR images with Photoshop Javascript Scripting
HDTR images with Photoshop Javascript Scripting
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
A real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodbA real systemwithjms-rest-protobuf-mongodb
A real systemwithjms-rest-protobuf-mongodb
 
Spring Data y Mongo DB en un proyecto Real
Spring Data y Mongo DB en un proyecto RealSpring Data y Mongo DB en un proyecto Real
Spring Data y Mongo DB en un proyecto Real
 

Recently uploaded

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 

Recently uploaded (20)

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 

Java 8 Stream API. A different way to process collections.

  • 1. Java8 Stream API A different way to process collections David Gómez G. @dgomezg dgomezg@autentia.com
  • 3. A Stream is… An convenience method to iterate over collections in a declarative way List<Integer>  numbers  =  new  ArrayList<Integer>();
 for  (int  i=  0;  i  <  100  ;  i++)  {
   numbers.add(i);
 }   List<Integer> evenNumbers = new ArrayList<>();
 for (int i : numbers) {
 if (i % 2 == 0) {
 evenNumbers.add(i);
 }
 } @dgomezg
  • 4. A Stream is… An convenience method to iterate over collections in a declarative way List<Integer>  numbers  =  new  ArrayList<Integer>();
 for  (int  i=  0;  i  <  100  ;  i++)  {
   numbers.add(i);
 }   List<Integer> evenNumbers = numbers.stream()
 .filter(n -> n % 2 == 0)
 .collect(toList()); @dgomezg
  • 5. So… Streams are collections? Not Really Collections Streams Sequence of elements Computed at construction In-memory data structure Sequence of elements Computed at iteration Traversable only Once External Iteration Internal Iteration Finite size Infinite size @dgomezg
  • 6. Iterating a Collection List<Integer> evenNumbers = new ArrayList<>();
 for (int i : numbers) {
 if (i % 2 == 0) {
 evenNumbers.add(i);
 }
 } External Iteration - Use forEach or Iterator - Very verbose Parallelism by manually using Threads - Concurrency is hard to be done right! - Lots of contention and error-prone - Thread-safety@dgomezg
  • 7. Iterating a Stream List<Integer> evenNumbers = numbers.stream()
 .filter(n -> n % 2 == 0)
 .collect(toList()); Internal Iteration - No manual Iterators handling - Concise - Fluent API: chain sequence processing Elements computed only when needed @dgomezg
  • 8. Iterating a Stream List<Integer> evenNumbers = numbers.parallelStream()
 .filter(n -> n % 2 == 0)
 .collect(toList()); Easily Parallelism - Concurrency is hard to be done right! - Uses ForkJoin - Process steps should be - stateless - independent @dgomezg
  • 10. @FunctionalInterface @FunctionalInterface
 public interface Predicate<T> { 
 boolean test(T t); ! ! ! ! ! } An interface with exactly one abstract method ! ! @dgomezg
  • 11. @FunctionalInterface @FunctionalInterface
 public interface Predicate<T> { 
 boolean test(T t); ! default Predicate<T> negate() {
 return (t) -> !test(t);
 } 
 ! } An interface with exactly one abstract method Could have default methods, though! ! @dgomezg
  • 12. Lambda Types Based on abstract method signature from @FunctionalInterface: (Arguments) -> <return type> @FunctionalInterface
 public interface Predicate<T> { 
 boolean test(T t); } T -> boolean @dgomezg
  • 13. Lambda Types Based on abstract method signature from @FunctionalInterface: (Arguments) -> <return type> @FunctionalInterface
 public interface Runnable { 
 void run(); } () -> void @dgomezg
  • 14. Lambda Types Based on abstract method signature from @FunctionalInterface: (Arguments) -> <return type> @FunctionalInterface
 public interface Supplier<T> { 
 T get(); } () -> T @dgomezg
  • 15. Lambda Types Based on abstract method signature from @FunctionalInterface: (Arguments) -> <return type> @FunctionalInterface
 public interface BiFunction<T, U, R> { 
 R apply(T t, U t); } (T, U) -> R @dgomezg
  • 16. Lambda Types Based on abstract method signature from @FunctionalInterface: (Arguments) -> <return type> @FunctionalInterface
 public interface Comparator<T> { 
 int compare(T o1, T o2); } (T, T) -> int @dgomezg
  • 17. Method References Allows to use a method name as a lambda Usually better readability ! Syntax: <TargetReference>::<MethodName> ! TargetReference: Instance or Class @dgomezg
  • 18. Method References phoneCall -> phoneCall.getContact() Method ReferenceLambda PhoneCall::getContact () -> Thread.currentThread() Thread::currentThread (str, c) -> str.indexOf(c) String::indexOf (String s) -> System.out.println(s) System.out::println @dgomezg
  • 20. Characteristics of A Stream • Interface to Sequence of elements • Focused on processing (not on storage) • Elements computed on demand (or extracted from source) • Can be traversed only once • Internal iteration • Parallel Support • Could be Infinite @dgomezg
  • 21. Anatomy of a Stream Source Intermediate Operations filter map order function Final operation pipeline @dgomezg
  • 22. Anatomy of Stream Iteration 1. Start from the DataSource (Usually a collection) and create the Stream List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 
 Stream<Integer> numbersStream = numbers.stream();
 @dgomezg
  • 23. Anatomy of Stream Iteration 2. Add a chain of intermediate Operations (Stream Pipeline) Stream<Integer> numbersStream = numbers.stream()
 .filter(new Predicate<Integer>() {
 @Override
 public boolean test(Integer number) {
 return number % 2 == 0;
 }
 }) ! .map(new Function<Integer, Integer>() {
 @Override
 public Integer apply(Integer number) {
 return number * 2;
 }
 }); @dgomezg
  • 24. Anatomy of Stream Iteration 2. Add a chain of intermediate Operations (Stream Pipeline) - Better using lambdas Stream<Integer> numbersStream = numbers.stream()
 .filter(number -> number % 2 == 0)
 .map(number -> number * 2); @dgomezg
  • 25. Anatomy of Stream Iteration 3. Close with a Terminal Operation List<Integer> numbersStream = numbers.stream()
 .filter(number -> number % 2 == 0)
 .map(number -> number * 2) .collect(Collectors.toList()); •The terminal operation triggers Stream Iteration •Before that, nothing is computed. •Depending on the terminal operation, the stream could be fully traversed or not. @dgomezg
  • 27. Operation Types Intermediate operations • Always return a Stream • Chain as many as needed (Pipeline) • Guide processing of data • Does not start processing • Can be Stateless or Stateful Terminal operations • Can return an object, a collection, or void • Start the pipeline process • After its execution, the Stream can not be revisited
  • 28. Intermediate Operations // T -> boolean Stream<T> filter(Predicate<? super T> predicate); ! //T -> R
 <R> Stream<R> map(Function<? super T, ? extends R> mapper); 
 //(T,T) -> int
 Stream<T> sorted(Comparator<? super T> comparator); Stream<T> sorted(); ! //T -> void
 Stream<T> peek(Consumer<? super T> action); ! Stream<T> distinct();
 Stream<T> limit(long maxSize);
 Stream<T> skip(long n); @dgomezg
  • 29. Final Operations Object[] toArray(); void forEach(Consumer<? super T> action); //T -> void
 <R, A> R collect(Collector<? super T, A, R> collector);
 ! ! java.util.stream.Collectors.toList(); java.util.stream.Collectors.toSet(); java.util.stream.Collectors.toMap(); java.util.stream.Collectors.joining(CharSequence); ! ! ! @dgomezg
  • 30. Final Operations (II) //T,U -> R Optional<T> reduce(BinaryOperator<T> accumulator); //(T,T) -> int
 Optional<T> min(Comparator<? super T> comparator);
 //(T,T) -> int Optional<T> max(Comparator<? super T> comparator);
 long count();
 ! @dgomezg
  • 31. Final Operations (y III) //T -> boolean boolean anyMatch(Predicate<? super T> predicate);
 boolean allMatch(Predicate<? super T> predicate);
 boolean noneMatch(Predicate<? super T> predicate);
 ! @dgomezg
  • 32. Usage examples - Context public class Contact {
 private final String name;
 private final String city;
 private final String phoneNumber;
 private final LocalDate birth;
 
 
 public int getAge() {
 return Period.between(birth, LocalDate.now())
 .getYears();
 }
 //Constructor and getters omitted
 ! }
 @dgomezg
  • 33. Usage examples - Context public class PhoneCall {
 private final Contact contact;
 private final LocalDate time;
 private final Duration duration;
 ! //Constructor and getters omitted }
 Contact me = new Contact("dgomezg", "Madrid", "555 55 55 55", LocalDate.of(1975, Month.MARCH, 26));
 Contact martin = new Contact("Martin", "Santiago", "666 66 66 66", LocalDate.of(1978, Month.JANUARY, 17));
 Contact roberto = new Contact("Roberto", "Santiago", "111 11 11 11", LocalDate.of(1973, Month.MAY, 11));
 Contact heinz = new Contact("Heinz", "Chania", "444 44 44 44", LocalDate.of(1972, Month.APRIL, 29));
 Contact michael = new Contact("michael", "Munich", "222 22 22 22", LocalDate.of(1976, Month.DECEMBER, 8));
 
 List<PhoneCall> phoneCallLog = Arrays.asList(
 new PhoneCall(heinz, LocalDate.of(2014, Month.MAY, 28), Duration.ofSeconds(125)),
 new PhoneCall(martin, LocalDate.of(2014, Month.MAY, 30), Duration.ofMinutes(5)),
 new PhoneCall(roberto, LocalDate.of(2014, Month.MAY, 30), Duration.ofMinutes(12)),
 new PhoneCall(michael, LocalDate.of(2014, Month.MAY, 28), Duration.ofMinutes(3)),
 new PhoneCall(michael, LocalDate.of(2014, Month.MAY, 29), Duration.ofSeconds(90)),
 new PhoneCall(heinz, LocalDate.of(2014, Month.MAY, 30), Duration.ofSeconds(365)),
 new PhoneCall(heinz, LocalDate.of(2014, Month.JUNE, 1), Duration.ofMinutes(7)),
 new PhoneCall(martin, LocalDate.of(2014, Month.JUNE, 2), Duration.ofSeconds(315))
 ) ; @dgomezg
  • 34. People I phoned in June phoneCallLog.stream()
 .filter(phoneCall -> phoneCall.getTime().getMonth() == Month.JUNE)
 .map(phoneCall -> phoneCall.getContact().getName())
 .distinct()
 .forEach(System.out::println);
 ! @dgomezg
  • 35. Seconds I talked in May Long total = phoneCallLog.stream()
 .filter(phoneCall -> phoneCall.getTime().getMonth() == Month.MAY)
 .map(PhoneCall::getDuration)
 .collect(summingLong(Duration::getSeconds)); @dgomezg
  • 36. Seconds I talked in May Optional<Long> total = phoneCallLog.stream()
 .filter(phoneCall -> phoneCall.getTime().getMonth() == Month.MAY)
 .map(PhoneCall::getDuration)
 .reduce(Duration::plus); 
 total.ifPresent(duration -> {System.out.println(duration.getSeconds());} );
 ! @dgomezg
  • 37. Did I phone to Paris? boolean phonedToParis = phoneCallLog.stream()
 .anyMatch(phoneCall -> "Paris".equals(phoneCall.getContact().getCity()))
 ! ! @dgomezg
  • 38. Give me the 3 longest phone calls phoneCallLog.stream()
 .filter(phoneCall -> phoneCall.getTime().getMonth() == Month.MAY)
 .sorted(comparing(PhoneCall::getDuration))
 .limit(3)
 .forEach(System.out::println); @dgomezg
  • 39. Give me the 3 shortest ones phoneCallLog.stream()
 .filter(phoneCall -> phoneCall.getTime().getMonth() == Month.MAY)
 .sorted(comparing(PhoneCall::getDuration).reversed())
 .limit(3)
 .forEach(System.out::println); @dgomezg
  • 41. Streams can be created from Collections Directly from values Generators (infinite Streams) Resources (like files) Stream ranges @dgomezg
  • 42. From collections use stream() List<Integer> numbers = new ArrayList<>();
 for (int i= 0; i < 10_000_000 ; i++) {
 numbers.add((int)Math.round(Math.random()*100));
 } Stream<Integer> evenNumbers = numbers.stream(); or parallelStream() Stream<Integer> evenNumbers = numbers.parallelStream(); @dgomezg
  • 43. Directly from Values & ranges Stream.of("Using", "Stream", "API", "From", “Java8”); can convert into parallelStream Stream.of("Using", "Stream", "API", "From", “Java8”) .parallel();
 @dgomezg
  • 44. Generators - Functions Stream<Integer> integers = Stream.iterate(0, number -> number + 2); This is an infinite Stream!, will never be exhausted! Stream fibonacci = Stream.iterate(new int[]{0,1}, t -> new int[]{t[1],t[0]+t[1]}); 
 fibonacci.limit(10)
 .map(t -> t[0])
 .forEach(System.out::println); @dgomezg
  • 45. Generators - Functions Stream<Integer> integers = Stream.iterate(0, number -> number + 2); This is an infinite Stream!, will never be exhausted! Stream fibonacci = Stream.iterate(new int[]{0,1}, t -> new int[]{t[1],t[0]+t[1]}); 
 fibonacci.limit(10)
 .map(t -> t[0])
 .forEach(System.out::println); @dgomezg
  • 46. From Resources (Files) Stream<String> fileContent = Files.lines(Paths.get(“readme.txt”)); Files.lines(Paths.get(“readme.txt”))
 .flatMap(line -> Arrays.stream(line.split(" ")))
 .distinct()
 .count());
 ! Count all distinct words in a file @dgomezg
  • 48. Parallel Streams use stream() List<Integer> numbers = new ArrayList<>();
 for (int i= 0; i < 10_000_000 ; i++) {
 numbers.add((int)Math.round(Math.random()*100));
 } //This will use just a single thread Stream<Integer> evenNumbers = numbers.stream(); or parallelStream() //Automatically select the optimum number of threads Stream<Integer> evenNumbers = numbers.parallelStream(); @dgomezg
  • 49. Let’s test it use stream() ! for (int i = 0; i < 100; i++) {
 long start = System.currentTimeMillis();
 List<Integer> even = numbers.stream()
 .filter(n -> n % 2 == 0)
 .sorted()
 .collect(toList()); 
 System.out.printf( "%d elements computed in %5d msecs with %d threadsn”,
 even.size(), System.currentTimeMillis() - start, Thread.activeCount());
 } 5001983 elements computed in 828 msecs with 2 threads 5001983 elements computed in 843 msecs with 2 threads 5001983 elements computed in 675 msecs with 2 threads 5001983 elements computed in 795 msecs with 2 threads @dgomezg
  • 50. Let’s test it use stream() ! for (int i = 0; i < 100; i++) {
 long start = System.currentTimeMillis();
 List<Integer> even = numbers.parallelStream()
 .filter(n -> n % 2 == 0)
 .sorted()
 .collect(toList()); 
 System.out.printf( "%d elements computed in %5d msecs with %d threadsn”,
 even.size(), System.currentTimeMillis() - start, Thread.activeCount());
 } 4999299 elements computed in 225 msecs with 9 threads 4999299 elements computed in 230 msecs with 9 threads 4999299 elements computed in 250 msecs with 9 threads @dgomezg
  • 51. Enough, for now, But this is just the beginning Thank You. @dgomezg dgomezg@gmail.com www.adictosaltrabajlo.com