SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Java 8 Stream API
Outline
• Stream Building Blocks
– Java 8
– Default Methods
– Functional Interfaces
– Lambda Expressions
– Method References
Outline
• Characteristics of Streams
• Creating Streams
• Common Functional Interfaces Used
• Anatomy of the Stream pipeline
• Optional Class
• Common Stream API Methods Used
– Examples
• Parallel Streams
• Unbounded (On the Fly) Streams
• What Could Streams Do For BMI
• References
• Questions?
Java 8
• Target Release Date: 03/18/14
• Introduces
– Default Methods
– Functional Interfaces
– Lambda Expressions
– Stream API and overall improvements to
Collections to support Streams
Default Methods
• In Context of Support For Streams
– Java 8 needed to add functionality to existing
Collection interfaces to support Streams (stream(),
forEach())
Default Methods
• Problem
– Pre-Java 8 interfaces couldn’t have method
bodies.
– The only way to add functionality to Interfaces
was to declare additional methods which would
be implemented in classes that implement the
interface
– It is impossible to add methods to an interface
without breaking the existing implementation
Default Methods
• Solution
– Default Methods!
– Java 8 allows default methods to be added to
interfaces with their full implementation
– Classes which implement the interface don’t have
to have implementations of the default method
– Allows the addition of functionality to interfaces
while preserving backward compatibility
Default Methods
• Example
public interface A {
default void foo(){
System.out.println("Calling A.foo()");
}
public class Clazz implements A {}
Clazz clazz = new Clazz();
clazz.foo(); // Calling A.foo()
Functional Interfaces
• Interfaces with only one abstract method.
• With only one abstract method, these
interfaces can be easily represented with
lambda expressions
• Example
@FunctionalInterface
public interface SimpleFuncInterface {
public void doWork();
}
Lambda expressions
• A more brief and clearly expressive way to implement functional interfaces
• Format: <Argument List> -> <Body>
• Example (Functional Interface)
public interface Predicate<T> {
boolean test(T input);
}
• Example (Static Method)
public static <T> Collection<T> filter(Predicate<T> predicate,
Collection<T> items) {
Collection<T> result = new ArrayList<T>();
for(T item: items) {
if(predicate.test(item)) {
result.add(item);
}
}
}
• Example (Call with Lambda Expression)
Collection<Integer> myInts = asList(0,1,2,3,4,5,6,7,8,9);
Collection<Integer> onlyOdds = filter(n -> n % 2 != 0, myInts)
Method References
• Event more brief and clearly expressive way to implement
functional interfaces
• Format: <Class or Instance>::<Method>
• Example (Functional Interface)
public interface IntPredicates {
boolean isOdd(Integer n) { return n % 2 != 0; }
}
• Example (Call with Lambda Expression)
List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9);
List<Integer> odds = filter(n -> IntPredicates.isOdd(n), numbers);
• Example (Call with Method Reference)
List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9);
List<Integer> odds = filter(IntPredicates::isOdd, numbers);
Characteristics of Streams
• Streams are not related to InputStreams, OutputStreams, etc.
• Streams are NOT data structures but are wrappers around
Collection that carry values from a source through a pipeline of
operations.
• Streams are more powerful, faster and more memory efficient than
Lists
• Streams are designed for lambdas
• Streams can easily be output as arrays or lists
• Streams employ lazy evaluation
• Streams are parallelizable
• Streams can be “on-the-fly”
Creating Streams
• From individual values
– Stream.of(val1, val2, …)
• From array
– Stream.of(someArray)
– Arrays.stream(someArray)
• From List (and other Collections)
– someList.stream()
– someOtherCollection.stream()
Common Functional Interfaces Used
• Predicate<T>
– Represents a predicate (boolean-valued function) of one argument
– Functional method is boolean Test(T t)
• Evaluates this Predicate on the given input argument (T t)
• Returns true if the input argument matches the predicate, otherwise false
• Supplier<T>
– Represents a supplier of results
– Functional method is T get()
• Returns a result of type T
• Function<T,R>
– Represents a function that accepts one argument and produces a result
– Functional method is R apply(T t)
• Applies this function to the given argument (T t)
• Returns the function result
• Consumer<T>
– Represents an operation that accepts a single input and returns no result
– Functional method is void accept(T t)
• Performs this operation on the given argument (T t)
Common Functional Interfaces Used
• Function<T,R>
– Represents an operation that accepts one argument and produces
a result
– Functional method is R apply(T t)
• Applies this function to the given argument (T t)
• Returns the function result
• UnaryOperator<T>
– Represents an operation on a single operands that produces a
result of the same type as its operand
– Functional method is R Function.apply(T t)
• Applies this function to the given argument (T t)
• Returns the function result
Common Functional Interfaces Used
• BiFunction<T,U,R>
– Represents an operation that accepts two arguments and produces a result
– Functional method is R apply(T t, U u)
• Applies this function to the given arguments (T t, U u)
• Returns the function result
• BinaryOperator<T>
– Extends BiFunction<T, U, R>
– Represents an operation upon two operands of the same type, producing a result of the same type
as the operands
– Functional method is R BiFunction.apply(T t, U u)
• Applies this function to the given arguments (T t, U u) where R,T and U are of the same type
• Returns the function result
• Comparator<T>
– Compares its two arguments for order.
– Functional method is int compareTo(T o1, T o2)
• Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or
greater than the second.
Anatomy of the Stream Pipeline
• A Stream is processed through a pipeline of operations
• A Stream starts with a source data structure
• Intermediate methods are performed on the Stream
elements. These methods produce Streams and are not
processed until the terminal method is called.
• The Stream is considered consumed when a terminal
operation is invoked. No other operation can be performed on
the Stream elements afterwards
• A Stream pipeline contains some short-circuit methods (which
could be intermediate or terminal methods) that cause the
earlier intermediate methods to be processed only until the
short-circuit method can be evaluated.
Anatomy of the Stream Pipeline
• Intermediate Methods
map, filter, distinct, sorted, peek, limit,
parallel
• Terminal Methods
forEach, toArray, reduce, collect, min,
max, count, anyMatch, allMatch, noneMatch, findFirst,
findAny, iterator
• Short-circuit Methods
anyMatch, allMatch, noneMatch, findFirst, findAny,limit
Optional<T> Class
• A container which may or may not
contain a non-null value
• Common methods
– isPresent() – returns true if value is present
– Get() – returns value if present
– orElse(T other) – returns value if present, or
other
– ifPresent(Consumer) – runs the lambda if value
is present
Common Stream API Methods Used
• Void forEach(Consumer)
–Easy way to loop over Stream elements
–You supply a lambda for forEach and that
lambda is called on each element of the
Stream
–Related peek method does the exact
same thing, but returns the original
Stream
Common Stream API Methods Used
• Void forEach(Consumer)
–Example
Employees.forEach(e ->
e.setSalary(e.getSalary() * 11/10))
Give all employees a 10% raise
Common Stream API Methods Used
• Void forEach(Consumer)
–Vs. For Loops
List<Employee> employees = getEmployees();
for(Employee e: employees) {
e.setSalary(e.getSalary() * 11/10);
}
–Advantages of forEach
• Designed for lambdas to be marginally more succinct
• Lambdas are reusable
• Can be made parallel with minimal effort
Common Stream API Methods Used
• Stream<T> map(Function)
–Produces a new Stream that is the result
of applying a Function to each element of
original Stream
–Example
Ids.map(EmployeeUtils::findEmployeeById)
Create a new Stream of Employee ids
Common Stream API Methods Used
• Stream<T> filter(Predicate)
–Produces a new Stream that contains
only the elements of the original Stream
that pass a given test
–Example
employees.filter(e -> e.getSalary() > 100000)
Produce a Stream of Employees with a high
salary
Common Stream API Methods Used
• Optional<T> findFirst()
–Returns an Optional for the first entry in
the Stream
–Example
employees.filter(…).findFirst().orElse(Consul
tant)
Get the first Employee entry that passes the
filter
Common Stream API Methods Used
• Object[] toArray(Supplier)
–Reads the Stream of elements into a an
array
–Example
Employee[] empArray =
employees.toArray(Employee[]::new);
Create an array of Employees out of the
Stream of Employees
Common Stream API Methods Used
• List<T> collect(Collectors.toList())
• Reads the Stream of elements into a List or any
other collection
– Example
List<Employee> empList =
employees.collect(Collectors.toList());
Create a List of Employees out of the Stream of
Employees
Common Stream API Methods Used
• List<T> collect(Collectors.toList())
– partitioningBy
• You provide a Predicate. It builds a Map where true maps to a List
of entries that passed the Predicate, and false maps to a List that
failed the Predicate.
• Example
Map<Boolean,List<Employee>> richTable =
googlers().collect
(partitioningBy(e -> e.getSalary() > 1000000));
– groupingBy
• You provide a Function. It builds a Map where each output value
of the Function maps to a List of entries that gave that value.
• Example
Map<Department,List<Employee>> deptTable =
employeeStream().collect(groupingBy(Employee::getDepartment));
Common Stream API Methods Used
• T reduce(T identity, BinaryOperator)
• You start with a seed (identity) value, then combine
this value with the first Entry in the Stream, combine
the second entry of the Stream, etc.
– Example
Nums.stream().reduce(1, (n1,n2) -> n1*n2)
Calculate the product of numbers
• IntStream (Stream on primative int] has build-in
sum()
• Built-in Min, Max methods
Common Stream API Methods Used
• Stream<T> limit(long
maxSize)
• Limit(n) returns a stream of the first n
elements
–Example
someLongStream.limit(10)
First 10 elements
Common Stream API Methods Used
•Stream<T> skip(long n)
• skip(n) returns a stream starting
with element n
–Example
twentyElementStream.skip(5)
Last 15 elements
Common Stream API Methods Used
• Stream<T> sorted(Comparator)
– Returns a stream consisting of the elements of
this stream, sorted according to the provided
Comparator
– Example
empStream.map(…).filter(…).limit(…)
.sorted((e1, e2) -> e1.getSalary() -
e2.getSalary())
Employees sorted by salary
Common Stream API Methods Used
• Optional<T> min(Comparator)
– Returns the minimum element in this Stream according to the
Comparator
– Example
Employee alphabeticallyFirst =
ids.stream().map(EmployeeSamples::findGoogler)
.min((e1, e2) ->
e1.getLastName()
.compareTo(e2.getLastName()))
.get();
Get Googler with earliest lastName
Common Stream API Methods Used
• Optional<T> max(Comparator)
– Returns the minimum element in this Stream according to
the Comparator
– Example
Employee richest =
ids.stream().map(EmployeeSamples::findGoogler)
.max((e1, e2) -> e1.getSalary() -
e2.getSalary())
.get();
Get Richest Employee
Common Stream API Methods Used
• Stream<T> distinct()
– Returns a stream consisting of the distinct elements of this stream
– Example
List<Integer> ids2 =
Arrays.asList(9, 10, 9, 10, 9, 10);
List<Employee> emps4 =
ids2.stream().map(EmployeeSamples::findGoogler)
.distinct()
.collect(toList());
Get a list of distinct Employees
Common Stream API Methods Used
• Boolean anyMatch(Predicate), allMatch(Predicate),
noneMatch(Predicate)
– Returns true if Stream passes, false otherwise
– Lazy Evaluation
• anyMatch processes elements in the Stream one element at a time until it finds a
match according to the Predicate and returns true if it found a match
• allMatch processes elements in the Stream one element at a time until it fails a
match according to the Predicate and returns false if an element failed the
Predicate
• noneMatch processes elements in the Stream one element at a time until it finds a
match according to the Predicate and returns false if an element matches the
Predicate
– Example
employeeStream.anyMatch(e -> e.getSalary() > 500000)
Is there a rich Employee among all Employees?
Common Stream API Methods Used
• long count()
– Returns the count of elements in the Stream
– Example
employeeStream.filter(somePredicate).c
ount()
How many Employees match the
criteria?
Parallel Streams
• Helper Methods For Timing
private static void timingTest(Stream<Employee> testStream) {
long startTime = System.nanoTime();
testStream.forEach(e -> doSlowOp());
long endTime = System.nanoTime();
System.out.printf(" %.3f seconds.%n",
deltaSeconds(startTime, endTime));
}
private static double deltaSeconds(long startTime, long endTime) {
return((endTime - startTime) / 1000000000);
}
Parallel Streams
• Helper Method For Simulating Long Operation
void doSlowOp() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ie) {
// Nothing to do here.
}
}
Parallel Streams
• Main Code
System.out.print("Serial version [11 entries]:");
timingTest(googlers());
int numProcessorsOrCores =
Runtime.getRuntime().availableProcessors();
System.out.printf("Parallel version on %s-core
machine:",
numProcessorsOrCores);
timingTest(googlers().parallel() );
Parallel Streams
•Results
Serial version [11 entries]:
11.000 seconds.
Parallel version on 4-core
machine: 3.000 seconds.
(On The Fly) Streams
• Stream<T> generate(Supplier)
– The method lets you specify a Supplier
– This Supplier is invoked each time the system needs a Stream element
– Example
List<Employee> emps =
Stream.generate(() -> randomEmployee())
.limit(n)
.collect(toList());
• Stream<T> iterate(T seed, UnaryOperator<T> f)
– The method lets you specify a seed and a UnaryOperator.
– The seed becomes the first element of the Stream, f(seed) becomes the second element of the Stream,
f(second) becomes the third element, etc.
– Example
List<Integer> powersOfTwo =
Stream.iterate(1, n -> n * 2)
.limit(n)
.collect(toList());
• The values are not calculated until they are needed
• To avoid unterminated processing, you must eventually use a size-limiting method
• This is less of an actual Unbounded Stream and more of an “On The Fly” Stream
References
• Stream API
– http://download.java.net/jdk8/docs/api/java/util/stream/S
tream.html
• Java 8 Explained: Applying Lambdas to Java Collections
– http://zeroturnaround.com/rebellabs/java-8-explained-
applying-lambdas-to-java-collections/
• Java 8 first steps with Lambdas and Streams
– https://blog.codecentric.de/en/2013/10/java-8-first-steps-
lambdas-streams/
• Java 8Tutorial: Lambda Expressions, Streams, and More
– http://www.coreservlets.com/java-8-tutorial/
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda ExpressionsScott Leberknight
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambdaManav Prasad
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8Tobias Coetzee
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream apiVladislav sidlyarevich
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in javayugandhar vadlamudi
 
Java8 features
Java8 featuresJava8 features
Java8 featuresElias Hasnat
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernateelliando dias
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8Richard Walker
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 

Was ist angesagt? (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 

Ähnlich wie Java 8 streams

Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new featuresAniket Thakur
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature PreviewJim Bethancourt
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core FeaturesGlobalLogic Ukraine
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and LaughsJim Bethancourt
 
Java 8
Java 8Java 8
Java 8vpulec
 
Java8.part2
Java8.part2Java8.part2
Java8.part2Ivan Ivanov
 
Java 8 Functional Programming - I
Java 8 Functional Programming - IJava 8 Functional Programming - I
Java 8 Functional Programming - IUgur Yeter
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesBuddhini Seneviratne
 
Java 8 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesWSO2
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesBuddhini Seneviratne
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Isuru Samaraweera
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8Tobias Coetzee
 

Ähnlich wie Java 8 streams (20)

Java8
Java8Java8
Java8
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
java8
java8java8
java8
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Java 8
Java 8Java 8
Java 8
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
 
Java 8 Functional Programming - I
Java 8 Functional Programming - IJava 8 Functional Programming - I
Java 8 Functional Programming - I
 
Java8lambda
Java8lambda Java8lambda
Java8lambda
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8Exploring Streams and Lambdas in Java8
Exploring Streams and Lambdas in Java8
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 

Mehr von Manav Prasad

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoftManav Prasad
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
MulesoftconnectorsManav Prasad
 
Mule and web services
Mule and web servicesMule and web services
Mule and web servicesManav Prasad
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhubManav Prasad
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorialManav Prasad
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Spring introduction
Spring introductionSpring introduction
Spring introductionManav Prasad
 
The spring framework
The spring frameworkThe spring framework
The spring frameworkManav Prasad
 
Rest introduction
Rest introductionRest introduction
Rest introductionManav Prasad
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaManav Prasad
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5Manav Prasad
 

Mehr von Manav Prasad (20)

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jpa
JpaJpa
Jpa
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Json
Json Json
Json
 
The spring framework
The spring frameworkThe spring framework
The spring framework
 
Rest introduction
Rest introductionRest introduction
Rest introduction
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Junit
JunitJunit
Junit
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xpath
XpathXpath
Xpath
 
Xslt
XsltXslt
Xslt
 
Xhtml
XhtmlXhtml
Xhtml
 
Css
CssCss
Css
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
 
Ajax
AjaxAjax
Ajax
 

KĂźrzlich hochgeladen

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 

KĂźrzlich hochgeladen (20)

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 

Java 8 streams

  • 2. Outline • Stream Building Blocks – Java 8 – Default Methods – Functional Interfaces – Lambda Expressions – Method References
  • 3. Outline • Characteristics of Streams • Creating Streams • Common Functional Interfaces Used • Anatomy of the Stream pipeline • Optional Class • Common Stream API Methods Used – Examples • Parallel Streams • Unbounded (On the Fly) Streams • What Could Streams Do For BMI • References • Questions?
  • 4. Java 8 • Target Release Date: 03/18/14 • Introduces – Default Methods – Functional Interfaces – Lambda Expressions – Stream API and overall improvements to Collections to support Streams
  • 5. Default Methods • In Context of Support For Streams – Java 8 needed to add functionality to existing Collection interfaces to support Streams (stream(), forEach())
  • 6. Default Methods • Problem – Pre-Java 8 interfaces couldn’t have method bodies. – The only way to add functionality to Interfaces was to declare additional methods which would be implemented in classes that implement the interface – It is impossible to add methods to an interface without breaking the existing implementation
  • 7. Default Methods • Solution – Default Methods! – Java 8 allows default methods to be added to interfaces with their full implementation – Classes which implement the interface don’t have to have implementations of the default method – Allows the addition of functionality to interfaces while preserving backward compatibility
  • 8. Default Methods • Example public interface A { default void foo(){ System.out.println("Calling A.foo()"); } public class Clazz implements A {} Clazz clazz = new Clazz(); clazz.foo(); // Calling A.foo()
  • 9. Functional Interfaces • Interfaces with only one abstract method. • With only one abstract method, these interfaces can be easily represented with lambda expressions • Example @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); }
  • 10. Lambda expressions • A more brief and clearly expressive way to implement functional interfaces • Format: <Argument List> -> <Body> • Example (Functional Interface) public interface Predicate<T> { boolean test(T input); } • Example (Static Method) public static <T> Collection<T> filter(Predicate<T> predicate, Collection<T> items) { Collection<T> result = new ArrayList<T>(); for(T item: items) { if(predicate.test(item)) { result.add(item); } } } • Example (Call with Lambda Expression) Collection<Integer> myInts = asList(0,1,2,3,4,5,6,7,8,9); Collection<Integer> onlyOdds = filter(n -> n % 2 != 0, myInts)
  • 11. Method References • Event more brief and clearly expressive way to implement functional interfaces • Format: <Class or Instance>::<Method> • Example (Functional Interface) public interface IntPredicates { boolean isOdd(Integer n) { return n % 2 != 0; } } • Example (Call with Lambda Expression) List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9); List<Integer> odds = filter(n -> IntPredicates.isOdd(n), numbers); • Example (Call with Method Reference) List<Integer> numbers = asList(1,2,3,4,5,6,7,8,9); List<Integer> odds = filter(IntPredicates::isOdd, numbers);
  • 12. Characteristics of Streams • Streams are not related to InputStreams, OutputStreams, etc. • Streams are NOT data structures but are wrappers around Collection that carry values from a source through a pipeline of operations. • Streams are more powerful, faster and more memory efficient than Lists • Streams are designed for lambdas • Streams can easily be output as arrays or lists • Streams employ lazy evaluation • Streams are parallelizable • Streams can be “on-the-fly”
  • 13. Creating Streams • From individual values – Stream.of(val1, val2, …) • From array – Stream.of(someArray) – Arrays.stream(someArray) • From List (and other Collections) – someList.stream() – someOtherCollection.stream()
  • 14. Common Functional Interfaces Used • Predicate<T> – Represents a predicate (boolean-valued function) of one argument – Functional method is boolean Test(T t) • Evaluates this Predicate on the given input argument (T t) • Returns true if the input argument matches the predicate, otherwise false • Supplier<T> – Represents a supplier of results – Functional method is T get() • Returns a result of type T • Function<T,R> – Represents a function that accepts one argument and produces a result – Functional method is R apply(T t) • Applies this function to the given argument (T t) • Returns the function result • Consumer<T> – Represents an operation that accepts a single input and returns no result – Functional method is void accept(T t) • Performs this operation on the given argument (T t)
  • 15. Common Functional Interfaces Used • Function<T,R> – Represents an operation that accepts one argument and produces a result – Functional method is R apply(T t) • Applies this function to the given argument (T t) • Returns the function result • UnaryOperator<T> – Represents an operation on a single operands that produces a result of the same type as its operand – Functional method is R Function.apply(T t) • Applies this function to the given argument (T t) • Returns the function result
  • 16. Common Functional Interfaces Used • BiFunction<T,U,R> – Represents an operation that accepts two arguments and produces a result – Functional method is R apply(T t, U u) • Applies this function to the given arguments (T t, U u) • Returns the function result • BinaryOperator<T> – Extends BiFunction<T, U, R> – Represents an operation upon two operands of the same type, producing a result of the same type as the operands – Functional method is R BiFunction.apply(T t, U u) • Applies this function to the given arguments (T t, U u) where R,T and U are of the same type • Returns the function result • Comparator<T> – Compares its two arguments for order. – Functional method is int compareTo(T o1, T o2) • Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
  • 17. Anatomy of the Stream Pipeline • A Stream is processed through a pipeline of operations • A Stream starts with a source data structure • Intermediate methods are performed on the Stream elements. These methods produce Streams and are not processed until the terminal method is called. • The Stream is considered consumed when a terminal operation is invoked. No other operation can be performed on the Stream elements afterwards • A Stream pipeline contains some short-circuit methods (which could be intermediate or terminal methods) that cause the earlier intermediate methods to be processed only until the short-circuit method can be evaluated.
  • 18. Anatomy of the Stream Pipeline • Intermediate Methods map, filter, distinct, sorted, peek, limit, parallel • Terminal Methods forEach, toArray, reduce, collect, min, max, count, anyMatch, allMatch, noneMatch, findFirst, findAny, iterator • Short-circuit Methods anyMatch, allMatch, noneMatch, findFirst, findAny,limit
  • 19. Optional<T> Class • A container which may or may not contain a non-null value • Common methods – isPresent() – returns true if value is present – Get() – returns value if present – orElse(T other) – returns value if present, or other – ifPresent(Consumer) – runs the lambda if value is present
  • 20. Common Stream API Methods Used • Void forEach(Consumer) –Easy way to loop over Stream elements –You supply a lambda for forEach and that lambda is called on each element of the Stream –Related peek method does the exact same thing, but returns the original Stream
  • 21. Common Stream API Methods Used • Void forEach(Consumer) –Example Employees.forEach(e -> e.setSalary(e.getSalary() * 11/10)) Give all employees a 10% raise
  • 22. Common Stream API Methods Used • Void forEach(Consumer) –Vs. For Loops List<Employee> employees = getEmployees(); for(Employee e: employees) { e.setSalary(e.getSalary() * 11/10); } –Advantages of forEach • Designed for lambdas to be marginally more succinct • Lambdas are reusable • Can be made parallel with minimal effort
  • 23. Common Stream API Methods Used • Stream<T> map(Function) –Produces a new Stream that is the result of applying a Function to each element of original Stream –Example Ids.map(EmployeeUtils::findEmployeeById) Create a new Stream of Employee ids
  • 24. Common Stream API Methods Used • Stream<T> filter(Predicate) –Produces a new Stream that contains only the elements of the original Stream that pass a given test –Example employees.filter(e -> e.getSalary() > 100000) Produce a Stream of Employees with a high salary
  • 25. Common Stream API Methods Used • Optional<T> findFirst() –Returns an Optional for the first entry in the Stream –Example employees.filter(…).findFirst().orElse(Consul tant) Get the first Employee entry that passes the filter
  • 26. Common Stream API Methods Used • Object[] toArray(Supplier) –Reads the Stream of elements into a an array –Example Employee[] empArray = employees.toArray(Employee[]::new); Create an array of Employees out of the Stream of Employees
  • 27. Common Stream API Methods Used • List<T> collect(Collectors.toList()) • Reads the Stream of elements into a List or any other collection – Example List<Employee> empList = employees.collect(Collectors.toList()); Create a List of Employees out of the Stream of Employees
  • 28. Common Stream API Methods Used • List<T> collect(Collectors.toList()) – partitioningBy • You provide a Predicate. It builds a Map where true maps to a List of entries that passed the Predicate, and false maps to a List that failed the Predicate. • Example Map<Boolean,List<Employee>> richTable = googlers().collect (partitioningBy(e -> e.getSalary() > 1000000)); – groupingBy • You provide a Function. It builds a Map where each output value of the Function maps to a List of entries that gave that value. • Example Map<Department,List<Employee>> deptTable = employeeStream().collect(groupingBy(Employee::getDepartment));
  • 29. Common Stream API Methods Used • T reduce(T identity, BinaryOperator) • You start with a seed (identity) value, then combine this value with the first Entry in the Stream, combine the second entry of the Stream, etc. – Example Nums.stream().reduce(1, (n1,n2) -> n1*n2) Calculate the product of numbers • IntStream (Stream on primative int] has build-in sum() • Built-in Min, Max methods
  • 30. Common Stream API Methods Used • Stream<T> limit(long maxSize) • Limit(n) returns a stream of the first n elements –Example someLongStream.limit(10) First 10 elements
  • 31. Common Stream API Methods Used •Stream<T> skip(long n) • skip(n) returns a stream starting with element n –Example twentyElementStream.skip(5) Last 15 elements
  • 32. Common Stream API Methods Used • Stream<T> sorted(Comparator) – Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator – Example empStream.map(…).filter(…).limit(…) .sorted((e1, e2) -> e1.getSalary() - e2.getSalary()) Employees sorted by salary
  • 33. Common Stream API Methods Used • Optional<T> min(Comparator) – Returns the minimum element in this Stream according to the Comparator – Example Employee alphabeticallyFirst = ids.stream().map(EmployeeSamples::findGoogler) .min((e1, e2) -> e1.getLastName() .compareTo(e2.getLastName())) .get(); Get Googler with earliest lastName
  • 34. Common Stream API Methods Used • Optional<T> max(Comparator) – Returns the minimum element in this Stream according to the Comparator – Example Employee richest = ids.stream().map(EmployeeSamples::findGoogler) .max((e1, e2) -> e1.getSalary() - e2.getSalary()) .get(); Get Richest Employee
  • 35. Common Stream API Methods Used • Stream<T> distinct() – Returns a stream consisting of the distinct elements of this stream – Example List<Integer> ids2 = Arrays.asList(9, 10, 9, 10, 9, 10); List<Employee> emps4 = ids2.stream().map(EmployeeSamples::findGoogler) .distinct() .collect(toList()); Get a list of distinct Employees
  • 36. Common Stream API Methods Used • Boolean anyMatch(Predicate), allMatch(Predicate), noneMatch(Predicate) – Returns true if Stream passes, false otherwise – Lazy Evaluation • anyMatch processes elements in the Stream one element at a time until it finds a match according to the Predicate and returns true if it found a match • allMatch processes elements in the Stream one element at a time until it fails a match according to the Predicate and returns false if an element failed the Predicate • noneMatch processes elements in the Stream one element at a time until it finds a match according to the Predicate and returns false if an element matches the Predicate – Example employeeStream.anyMatch(e -> e.getSalary() > 500000) Is there a rich Employee among all Employees?
  • 37. Common Stream API Methods Used • long count() – Returns the count of elements in the Stream – Example employeeStream.filter(somePredicate).c ount() How many Employees match the criteria?
  • 38. Parallel Streams • Helper Methods For Timing private static void timingTest(Stream<Employee> testStream) { long startTime = System.nanoTime(); testStream.forEach(e -> doSlowOp()); long endTime = System.nanoTime(); System.out.printf(" %.3f seconds.%n", deltaSeconds(startTime, endTime)); } private static double deltaSeconds(long startTime, long endTime) { return((endTime - startTime) / 1000000000); }
  • 39. Parallel Streams • Helper Method For Simulating Long Operation void doSlowOp() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ie) { // Nothing to do here. } }
  • 40. Parallel Streams • Main Code System.out.print("Serial version [11 entries]:"); timingTest(googlers()); int numProcessorsOrCores = Runtime.getRuntime().availableProcessors(); System.out.printf("Parallel version on %s-core machine:", numProcessorsOrCores); timingTest(googlers().parallel() );
  • 41. Parallel Streams •Results Serial version [11 entries]: 11.000 seconds. Parallel version on 4-core machine: 3.000 seconds.
  • 42. (On The Fly) Streams • Stream<T> generate(Supplier) – The method lets you specify a Supplier – This Supplier is invoked each time the system needs a Stream element – Example List<Employee> emps = Stream.generate(() -> randomEmployee()) .limit(n) .collect(toList()); • Stream<T> iterate(T seed, UnaryOperator<T> f) – The method lets you specify a seed and a UnaryOperator. – The seed becomes the first element of the Stream, f(seed) becomes the second element of the Stream, f(second) becomes the third element, etc. – Example List<Integer> powersOfTwo = Stream.iterate(1, n -> n * 2) .limit(n) .collect(toList()); • The values are not calculated until they are needed • To avoid unterminated processing, you must eventually use a size-limiting method • This is less of an actual Unbounded Stream and more of an “On The Fly” Stream
  • 43. References • Stream API – http://download.java.net/jdk8/docs/api/java/util/stream/S tream.html • Java 8 Explained: Applying Lambdas to Java Collections – http://zeroturnaround.com/rebellabs/java-8-explained- applying-lambdas-to-java-collections/ • Java 8 first steps with Lambdas and Streams – https://blog.codecentric.de/en/2013/10/java-8-first-steps- lambdas-streams/ • Java 8Tutorial: Lambda Expressions, Streams, and More – http://www.coreservlets.com/java-8-tutorial/