The document outlines Java 8's Stream API. It discusses stream building blocks like default methods, functional interfaces, lambda expressions, and method references. It describes characteristics of streams like laziness and parallelization. It covers creating streams from collections, common functional interfaces, and the anatomy of a stream pipeline including intermediate and terminal operations. It provides examples of common stream API methods like forEach, map, filter, findFirst, toArray, collect, and reduce.
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
This is a beginner's guide to Java 8 Lambdas, accompnied with executable code examples which you can find at https://github.com/manvendrasinghkadam/java8streams. Java 8 Streams are based on Lambdas, so this presentation assumes you know Lambdas quite well. If don't then please let me know I'll create another presentation regarding it with code examples. Lambdas are relatively easy to use and with the power of stream api you can do functional programming in Java right from start. This is very cool to be a Java programmer now.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
This is a beginner's guide to Java 8 Lambdas, accompnied with executable code examples which you can find at https://github.com/manvendrasinghkadam/java8streams. Java 8 Streams are based on Lambdas, so this presentation assumes you know Lambdas quite well. If don't then please let me know I'll create another presentation regarding it with code examples. Lambdas are relatively easy to use and with the power of stream api you can do functional programming in Java right from start. This is very cool to be a Java programmer now.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
Building a REST Service in minutes with Spring BootOmri Spector
A walk through building a micro service using Spring Boot.
Deck presented at Java 2016
Source accompanying presentation can be found at https://github.com/ospector/sbdemo
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
The Spring Framework has always embraced testing as a first class citizen. Spring-based components should be modular, easy to wire together via dependency injection, and therefore easy to test. In fact, when well designed following a POJO programming model, a component in a Spring application can be unit tested without using Spring at all. And when you take the step toward developing integration tests, Spring's testing support is there to make your job easy.
Join Spring Test component lead Sam Brannen in this talk to learn about the basics for Spring's unit and integration testing support. This talk will provide attendees an overview of the following topics: unit testing without Spring, integration testing with Spring, loading application contexts (with and without context hierarchies), injecting dependencies into tests, transaction management for tests, SQL script execution, testing Spring MVC and REST web applications, and more.
JOHN HUMPHREYS VP OF ENGINEERING INFRASTRUCTURE SYSTEMS, NOMURA
Spring Boot is a modern and extensible development framework that aims (and succeeds!) to take as much pain as possible out of developing with Java. With just a few Maven dependencies, new or existing programs become runnable, init.d-compliant uber-JARs or uber-WARs with embedded web-servers and virtually zero-configuration, code or otherwise. As an added freebie, Spring Boot Actuator will provide your programs with amazing configuration-free production monitoring facilities that let you have RESTFUL endpoints serving live stack-traces, heap and GC statistics, database statuses, spring-bean definitions, and password-masked configuration file audits.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
Start programming in a more functional style in Java. This is the second in a two part series on lambdas and streams in Java 8 presented at the JoziJug.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Découvrez le framework web Spring Boot qui a la cote !
Apprenez comment son système d'auto-configuration fonctionne.
Live coding et exemple de migration vers Spring Boot sont de la partie.
Building a REST Service in minutes with Spring BootOmri Spector
A walk through building a micro service using Spring Boot.
Deck presented at Java 2016
Source accompanying presentation can be found at https://github.com/ospector/sbdemo
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
The Spring Framework has always embraced testing as a first class citizen. Spring-based components should be modular, easy to wire together via dependency injection, and therefore easy to test. In fact, when well designed following a POJO programming model, a component in a Spring application can be unit tested without using Spring at all. And when you take the step toward developing integration tests, Spring's testing support is there to make your job easy.
Join Spring Test component lead Sam Brannen in this talk to learn about the basics for Spring's unit and integration testing support. This talk will provide attendees an overview of the following topics: unit testing without Spring, integration testing with Spring, loading application contexts (with and without context hierarchies), injecting dependencies into tests, transaction management for tests, SQL script execution, testing Spring MVC and REST web applications, and more.
JOHN HUMPHREYS VP OF ENGINEERING INFRASTRUCTURE SYSTEMS, NOMURA
Spring Boot is a modern and extensible development framework that aims (and succeeds!) to take as much pain as possible out of developing with Java. With just a few Maven dependencies, new or existing programs become runnable, init.d-compliant uber-JARs or uber-WARs with embedded web-servers and virtually zero-configuration, code or otherwise. As an added freebie, Spring Boot Actuator will provide your programs with amazing configuration-free production monitoring facilities that let you have RESTFUL endpoints serving live stack-traces, heap and GC statistics, database statuses, spring-bean definitions, and password-masked configuration file audits.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
Start programming in a more functional style in Java. This is the second in a two part series on lambdas and streams in Java 8 presented at the JoziJug.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Découvrez le framework web Spring Boot qui a la cote !
Apprenez comment son système d'auto-configuration fonctionne.
Live coding et exemple de migration vers Spring Boot sont de la partie.
This presentaion provides and overview of the new features of Java 8, namely default methods, functional interfaces, lambdas, method references, streams and Optional vs NullPointerException.
This presentation by Arkadii Tetelman (Lead Software Engineer, GlobalLogic) was delivered at Java.io 3.0 conference in Kharkiv on March 22, 2016.
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
This slide contains short introduction to different elements of functional programming along with some specific techniques with which we use functional programming in Swift.
Slides aim to provide constructed information about functional programming in Java 8. To able to do that, Lambdas, Built-in Functional Interfaces and Optionals summarised with code examples.
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
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.
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?
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() );
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/