SlideShare a Scribd company logo
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 (20)

PPTX
Python programming Part -6
Megha V
 
PPTX
Java Methods
OXUS 20
 
PDF
Developing Applications with MySQL and Java for beginners
Saeid Zebardast
 
PDF
7 Habits For a More Functional Swift
Jason Larsen
 
PPTX
Parts of python programming language
Megha V
 
PDF
Modern C++ Concurrency API
Seok-joon Yun
 
PPT
Method overloading
Azaz Maverick
 
PPTX
Giving Clarity to LINQ Queries by Extending Expressions R2
Ed Charbeneau
 
PPTX
Iteration
Pooja B S
 
PPTX
13. Java text processing
Intro C# Book
 
PPTX
SQL Server Select Topics
Jay Coskey
 
PPTX
String Manipulation in Python
Pooja B S
 
PDF
Email Classifier using Spark 1.3 Mlib / ML Pipeline
leorick lin
 
PPTX
Python programming: Anonymous functions, String operations
Megha V
 
PDF
Porting to Python 3
Lennart Regebro
 
PDF
Java methods or Subroutines or Functions
Kuppusamy P
 
PPTX
4. method overloading
Indu Sharma Bhardwaj
 
Python programming Part -6
Megha V
 
Java Methods
OXUS 20
 
Developing Applications with MySQL and Java for beginners
Saeid Zebardast
 
7 Habits For a More Functional Swift
Jason Larsen
 
Parts of python programming language
Megha V
 
Modern C++ Concurrency API
Seok-joon Yun
 
Method overloading
Azaz Maverick
 
Giving Clarity to LINQ Queries by Extending Expressions R2
Ed Charbeneau
 
Iteration
Pooja B S
 
13. Java text processing
Intro C# Book
 
SQL Server Select Topics
Jay Coskey
 
String Manipulation in Python
Pooja B S
 
Email Classifier using Spark 1.3 Mlib / ML Pipeline
leorick lin
 
Python programming: Anonymous functions, String operations
Megha V
 
Porting to Python 3
Lennart Regebro
 
Java methods or Subroutines or Functions
Kuppusamy P
 
4. method overloading
Indu Sharma Bhardwaj
 

Similar to Using Java Streams (20)

PPTX
Java Hands-On Workshop
Arpit Poladia
 
PDF
Xlab #1: Advantages of functional programming in Java 8
XSolve
 
PPTX
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
PPTX
A brief tour of modern Java
Sina Madani
 
PPTX
javaprograming-COLLECTION FRAMEWORK-171012084019.pptx
aniketkumar02062003
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PDF
Clean Lambdas & Streams in Java8
Victor Rentea
 
PPTX
Java8 training - Class 1
Marut Singh
 
PPTX
collection framework in java
MANOJ KUMAR
 
ODP
Java Collections
parag
 
PPTX
FUNctional Programming in Java 8
Richard Walker
 
PDF
Java 8
vilniusjug
 
ZIP
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
Howard Lewis Ship
 
PPTX
Use of Apache Commons and Utilities
Pramod Kumar
 
PDF
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
PPT
Md08 collection api
Rakesh Madugula
 
PDF
A Sceptical Guide to Functional Programming
Garth Gilmour
 
PPTX
collectionframework-141116005344-conversion-gate01.pptx
hemanth248901
 
PDF
Java 8 Stream API and RxJava Comparison
José Paumard
 
Java Hands-On Workshop
Arpit Poladia
 
Xlab #1: Advantages of functional programming in Java 8
XSolve
 
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
A brief tour of modern Java
Sina Madani
 
javaprograming-COLLECTION FRAMEWORK-171012084019.pptx
aniketkumar02062003
 
Java 8 Lambda Expressions
Scott Leberknight
 
07. Java Array, Set and Maps
Intro C# Book
 
Clean Lambdas & Streams in Java8
Victor Rentea
 
Java8 training - Class 1
Marut Singh
 
collection framework in java
MANOJ KUMAR
 
Java Collections
parag
 
FUNctional Programming in Java 8
Richard Walker
 
Java 8
vilniusjug
 
Clojure: Functional Concurrency for the JVM (presented at Open Source Bridge)
Howard Lewis Ship
 
Use of Apache Commons and Utilities
Pramod Kumar
 
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Md08 collection api
Rakesh Madugula
 
A Sceptical Guide to Functional Programming
Garth Gilmour
 
collectionframework-141116005344-conversion-gate01.pptx
hemanth248901
 
Java 8 Stream API and RxJava Comparison
José Paumard
 
Ad

Recently uploaded (20)

PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Add Background Images to Charts in IBM SPSS Statistics Version 31.pdf
Version 1 Analytics
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PPTX
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
Everything you need to know about pricing & licensing Microsoft 365 Copilot f...
Q-Advise
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Add Background Images to Charts in IBM SPSS Statistics Version 31.pdf
Version 1 Analytics
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
iaas vs paas vs saas :choosing your cloud strategy
CloudlayaTechnology
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Everything you need to know about pricing & licensing Microsoft 365 Copilot f...
Q-Advise
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
UITP Summit Meep Pitch may 2025 MaaS Rebooted
campoamor1
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Ad

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(",")); }