SlideShare a Scribd company logo
1 of 31
Download to read offline
Using Java Streams
OpenMarket @ Women Who Code
Synopsis
In this workshop you'll learn how to use Streams in Java, and why they're great!
Some brief introductory slides will be followed by a hands-on workshop, in
which you'll write your own Streams-based code to solve problems.
Prerequisites:
● Basic Java knowledge
● A Java 8 development environment
What is a stream?
● An alternative to conventional iteration.
● Using a stream, you can process data in a declarative way similar to SQL
statements.
● A pipeline of functions that can be evaluated.
● A flow of objects that be filtered, transformed, collected.
Example of a stream
List redWidgets = widgets.stream()
.filter(w -> w.getColor() == RED)
.collect(Collectors.toList());
What is a stream not?
● Not a data structure
● Should not mutate data
Why use them?
● Easier to read and comprehend
● Usually leads to shorter code
● Can bring parallelisation easily
● Gives you a vocabulary to solve problems, reducing errors
● Reduces temporary variable use
Operations
● Intermediate operators return streams eg map, filter, distinct
● Terminal operators return concrete types or produce a side effect eg
collect, forEach, sum
Example of a stream again
List redWidgets = widgets.stream()
.filter(w -> w.getColor() == RED)
.collect(Collectors.toList());
Lambdas
● Lambda expressions are otherwise known as anonymous functions
● They are not bound to identifiers
● They produce compact code
nameList.map(n -> System.out.println(“Hello “ + n));
Method References
● Method references are references to methods!
● They let us refer to a preexisting method
nameList.map(System.out::println)
Hands-on exercises
Exercise 1
private static void printUkNumbers(List<SmsMessage> messages) {
for (SmsMessage message : messages) {
if (message.phoneNumber().startsWith("44")) {
System.out.println(message.phoneNumber());
}
}
}
Example of a stream again
List redWidgets = widgets.stream()
.filter(w -> w.getColor() == RED)
.collect(Collectors.toList());
Exercise 1 with a stream
private static void printUkNumbersStream(List<SmsMessage> messages) {
messages.stream()
.filter(m -> m.phoneNumber().startsWith("44"))
.forEach(m -> System.out.println(m.phoneNumber()));
}
Exercise 2
private static void printLocalisedPhoneNumbers(List<SmsMessage> messages) {
for (SmsMessage message : messages) {
System.out.println(localisePhoneNumber(message.phoneNumber()));
}
}
private static String localisePhoneNumber(String phoneNumber) {
String suffix = phoneNumber.substring(2);
return 0 + suffix;
}
Exercise 2 with a stream
private static void printLocalisedPhoneNumbersStream(List<SmsMessage> messages) {
messages.stream()
.map(m -> localisePhoneNumber(m.phoneNumber()))
.forEach(phoneNumber -> System.out.println(phoneNumber));
}
Exercise 3
public static List<String> getAllMessageContent(List<SmsMessage> messages) {
List content = new LinkedList<String>();
for (SmsMessage message : messages) {
content.add(message.messageContent());
}
return content;
}
Exercise 3 with a stream
public static List<String> getAllMessageContentStream(List<SmsMessage> messages) {
return messages.stream()
.map(SmsMessage::messageContent)
.collect(Collectors.toList());
}
Exercise 4
public static Map<String, List<SmsMessage>> getUkMessagesPerKeyword(List<SmsMessage> messages) {
Map<String, List<SmsMessage>> out = new HashMap<>();
for (SmsMessage message : messages) {
if (message.phoneNumber().startsWith("44")) {
String keyword = message.messageContent().split(" ")[0].toUpperCase();
if (out.containsKey(keyword)) {
// append to existing list
List<SmsMessage> current = out.get(keyword);
current.add(message);
out.put(keyword, current);
}
else {
// create new list
List<SmsMessage> newList = new LinkedList<>();
newList.add(message);
out.put(keyword, newList);
}
}
}
return out;
}
Exercise 4 with a stream
public static Map<String, List<SmsMessage>> getUkMessagesPerKeywordStream(List<SmsMessage> messages) {
return messages.stream()
.filter(m -> m.phoneNumber().startsWith("44"))
.collect(Collectors.groupingBy(m -> m.messageContent().split(" ")[0].toUpperCase()));
}
Exercise 5
public static void main (String[] args) {
IntStream.range(1, 1000).forEach(num-> System.out.println(num);
}
Exercise 5 as parallel
public static void main (String[] args) {
IntStream.range(1, 1000).parallel().forEach(num-> System.out.println(num));
}
The books exercise
The task:
Get the surnames of the first fifteen authors over 50 years old, from our library
of books.
The books exercise
public static List<String> getSurnamesOfFirstFifteenAuthorsOver50(List<Book> library) {
List<String> surnames = new LinkedList<>();
Set<Author> authors = new HashSet<>();
for (Book book : library) {
if (book.getAuthor().getAge() >= 50) {
authors.add(book.getAuthor());
if (authors.size() >= 15) {
break;
}
}
}
for (Author author : authors) {
surnames.add(author.getSurname().toUpperCase());
}
return surnames;
}
The books exercise with a stream
public static List<String> getSurnamesOfFirstFifteenAuthorsOver50WithStreams(List<Book> library) {
return library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.distinct()
.limit(15)
.map(Author::getSurname)
.map(String::toUpperCase)
.collect(Collectors.toList());
}
More operations
Intermediate:
● skip
● flatmap
● peek
● sorted
Terminal:
● toArray
● reduce
● min/max
● count
● anyMatch
● findFirst
More collectors
// Compute sum of salaries of employee
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
// Partition students into passing and failing
Map<Boolean, List<Student>> passingFailing =
students.stream()
.collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
Gotchas
● Parallel streams use a globally shared thread pool.
● Stack traces are harder to read.
● Performance
Gotchas: non-terminating streams
IntStream.iterate(0, i -> ( i + 1 ) % 2)
.distinct()
.forEach(System.out::println);
Gotchas: checked exceptions
public String encodedAddressUsingTryCatch(String... address) {
return Arrays.stream(address)
.map(s -> {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.joining(","));
}
Thanks!
OpenMarket is hiring!
https://www.openmarket.com/company/careers/

More Related Content

What's hot

Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6Megha V
 
Java Methods
Java MethodsJava Methods
Java MethodsOXUS 20
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersSaeid Zebardast
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency APISeok-joon Yun
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Ed Charbeneau
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in PythonPooja B S
 
Email Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML PipelineEmail Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML Pipelineleorick lin
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsMegha V
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or FunctionsKuppusamy P
 

What's hot (20)

Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2Giving Clarity to LINQ Queries by Extending Expressions R2
Giving Clarity to LINQ Queries by Extending Expressions R2
 
Iteration
IterationIteration
Iteration
 
Overloadingmethod
OverloadingmethodOverloadingmethod
Overloadingmethod
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Email Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML PipelineEmail Classifier using Spark 1.3 Mlib / ML Pipeline
Email Classifier using Spark 1.3 Mlib / ML Pipeline
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or Functions
 
4. method overloading
4. method overloading4. method overloading
4. method overloading
 

Similar to Using Java Streams

New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useSharon Rozinsky
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hotSergii Maliarov
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)KonfHubTechConferenc
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8Sergiu Mircea Indrie
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8Raffi Khatchadourian
 

Similar to Using Java Streams (20)

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 or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Java 103
Java 103Java 103
Java 103
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 

Recently uploaded

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 

Recently uploaded (20)

Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 

Using Java Streams

  • 1. Using Java Streams OpenMarket @ Women Who Code
  • 2. Synopsis In this workshop you'll learn how to use Streams in Java, and why they're great! Some brief introductory slides will be followed by a hands-on workshop, in which you'll write your own Streams-based code to solve problems. Prerequisites: ● Basic Java knowledge ● A Java 8 development environment
  • 3. What is a stream? ● An alternative to conventional iteration. ● Using a stream, you can process data in a declarative way similar to SQL statements. ● A pipeline of functions that can be evaluated. ● A flow of objects that be filtered, transformed, collected.
  • 4. Example of a stream List redWidgets = widgets.stream() .filter(w -> w.getColor() == RED) .collect(Collectors.toList());
  • 5. What is a stream not? ● Not a data structure ● Should not mutate data
  • 6. Why use them? ● Easier to read and comprehend ● Usually leads to shorter code ● Can bring parallelisation easily ● Gives you a vocabulary to solve problems, reducing errors ● Reduces temporary variable use
  • 7. Operations ● Intermediate operators return streams eg map, filter, distinct ● Terminal operators return concrete types or produce a side effect eg collect, forEach, sum
  • 8. Example of a stream again List redWidgets = widgets.stream() .filter(w -> w.getColor() == RED) .collect(Collectors.toList());
  • 9. Lambdas ● Lambda expressions are otherwise known as anonymous functions ● They are not bound to identifiers ● They produce compact code nameList.map(n -> System.out.println(“Hello “ + n));
  • 10. Method References ● Method references are references to methods! ● They let us refer to a preexisting method nameList.map(System.out::println)
  • 12. Exercise 1 private static void printUkNumbers(List<SmsMessage> messages) { for (SmsMessage message : messages) { if (message.phoneNumber().startsWith("44")) { System.out.println(message.phoneNumber()); } } }
  • 13. Example of a stream again List redWidgets = widgets.stream() .filter(w -> w.getColor() == RED) .collect(Collectors.toList());
  • 14. Exercise 1 with a stream private static void printUkNumbersStream(List<SmsMessage> messages) { messages.stream() .filter(m -> m.phoneNumber().startsWith("44")) .forEach(m -> System.out.println(m.phoneNumber())); }
  • 15. Exercise 2 private static void printLocalisedPhoneNumbers(List<SmsMessage> messages) { for (SmsMessage message : messages) { System.out.println(localisePhoneNumber(message.phoneNumber())); } } private static String localisePhoneNumber(String phoneNumber) { String suffix = phoneNumber.substring(2); return 0 + suffix; }
  • 16. Exercise 2 with a stream private static void printLocalisedPhoneNumbersStream(List<SmsMessage> messages) { messages.stream() .map(m -> localisePhoneNumber(m.phoneNumber())) .forEach(phoneNumber -> System.out.println(phoneNumber)); }
  • 17. Exercise 3 public static List<String> getAllMessageContent(List<SmsMessage> messages) { List content = new LinkedList<String>(); for (SmsMessage message : messages) { content.add(message.messageContent()); } return content; }
  • 18. Exercise 3 with a stream public static List<String> getAllMessageContentStream(List<SmsMessage> messages) { return messages.stream() .map(SmsMessage::messageContent) .collect(Collectors.toList()); }
  • 19. Exercise 4 public static Map<String, List<SmsMessage>> getUkMessagesPerKeyword(List<SmsMessage> messages) { Map<String, List<SmsMessage>> out = new HashMap<>(); for (SmsMessage message : messages) { if (message.phoneNumber().startsWith("44")) { String keyword = message.messageContent().split(" ")[0].toUpperCase(); if (out.containsKey(keyword)) { // append to existing list List<SmsMessage> current = out.get(keyword); current.add(message); out.put(keyword, current); } else { // create new list List<SmsMessage> newList = new LinkedList<>(); newList.add(message); out.put(keyword, newList); } } } return out; }
  • 20. Exercise 4 with a stream public static Map<String, List<SmsMessage>> getUkMessagesPerKeywordStream(List<SmsMessage> messages) { return messages.stream() .filter(m -> m.phoneNumber().startsWith("44")) .collect(Collectors.groupingBy(m -> m.messageContent().split(" ")[0].toUpperCase())); }
  • 21. Exercise 5 public static void main (String[] args) { IntStream.range(1, 1000).forEach(num-> System.out.println(num); }
  • 22. Exercise 5 as parallel public static void main (String[] args) { IntStream.range(1, 1000).parallel().forEach(num-> System.out.println(num)); }
  • 23. The books exercise The task: Get the surnames of the first fifteen authors over 50 years old, from our library of books.
  • 24. The books exercise public static List<String> getSurnamesOfFirstFifteenAuthorsOver50(List<Book> library) { List<String> surnames = new LinkedList<>(); Set<Author> authors = new HashSet<>(); for (Book book : library) { if (book.getAuthor().getAge() >= 50) { authors.add(book.getAuthor()); if (authors.size() >= 15) { break; } } } for (Author author : authors) { surnames.add(author.getSurname().toUpperCase()); } return surnames; }
  • 25. The books exercise with a stream public static List<String> getSurnamesOfFirstFifteenAuthorsOver50WithStreams(List<Book> library) { return library.stream() .map(book -> book.getAuthor()) .filter(author -> author.getAge() >= 50) .distinct() .limit(15) .map(Author::getSurname) .map(String::toUpperCase) .collect(Collectors.toList()); }
  • 26. More operations Intermediate: ● skip ● flatmap ● peek ● sorted Terminal: ● toArray ● reduce ● min/max ● count ● anyMatch ● findFirst
  • 27. More collectors // Compute sum of salaries of employee int total = employees.stream() .collect(Collectors.summingInt(Employee::getSalary))); // Partition students into passing and failing Map<Boolean, List<Student>> passingFailing = students.stream() .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
  • 28. Gotchas ● Parallel streams use a globally shared thread pool. ● Stack traces are harder to read. ● Performance
  • 29. Gotchas: non-terminating streams IntStream.iterate(0, i -> ( i + 1 ) % 2) .distinct() .forEach(System.out::println);
  • 30. Gotchas: checked exceptions public String encodedAddressUsingTryCatch(String... address) { return Arrays.stream(address) .map(s -> { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }) .collect(Collectors.joining(",")); }