This presentation was given online in July 2017 and will be given at the NY Java SIG later this year. It progressively builds on Java 8 concepts using puzzles and coding to give students confidence in their Java 8 stream/lambda skills. Handouts and code in https://github.com/boyarsky/java-8-streams-by-puzzles
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This presentation covers Python most important data structures like Lists, Dictionaries, Sets and Tuples. Exception Handling and Random number generation using simple python module "random" also covered. Added simple python programs at the end of the presentation
Installing and Using Python
Basic I/O
Variables and Expressions
Conditional Code
Functions
Loops and Iteration
Python Data Structures
Errors and Exceptions
Object Oriented with Python
Multithreaded Programming with Python
Install/Create and Using Python Library
Compile Python Script
Resources
===========================
and 7 Quizzes
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This presentation covers Python most important data structures like Lists, Dictionaries, Sets and Tuples. Exception Handling and Random number generation using simple python module "random" also covered. Added simple python programs at the end of the presentation
Installing and Using Python
Basic I/O
Variables and Expressions
Conditional Code
Functions
Loops and Iteration
Python Data Structures
Errors and Exceptions
Object Oriented with Python
Multithreaded Programming with Python
Install/Create and Using Python Library
Compile Python Script
Resources
===========================
and 7 Quizzes
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
Inspired by Josh Bloch's Java Puzzlers, we put together our own Python Puzzlers. This slide deck brings you a set of 10 python puzzlers, that are fun and educational. Each puzzler will show you a piece of python code. Your task if to figure out what happens when the code is run. Whether you're a python beginner or a passionate python veteran, we hope that there's something to learn for everybody.
This slide deck was first presented at shopkick. Nandan Sawant and Ryan Rueth are engineers at shopkick. Keeping the audience in mind, most of the puzzlers are based on python 2.x.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Characteristics of Java and basic programming constructs like Data types, Variables, Operators, Control Statements, Arrays are discussed with relevant examples
Following a game show format made popular by Joshua Bloch and Neal Gafter's Java Puzzlers this presentation intends to both entertain and inform. Snippets of Python code the whose behaviour is not entirely obvious are shown, the audience will then be asked to pick from a number of options what the behaviour of the program is. The correct and sometimes non-intuitive answer will then be given along with a brief explanation of the idea the puzzle exposes. Only a modest working knowledge of the Python language is required to understand the puzzles, but the puzzles may also entertain the more experienced Python programmer.
These are the slides of the second part of this multi-part series, from Learn Python Den Haag meetup group. It covers List comprehensions, Dictionary comprehensions and functions.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
I gave this presentation at Code Camp. As a data scientist and backcountry skier, I was interested in looking at fatal avalanche data. This covers scraping the data, analysis with Python, pandas and IPython Notebook. The final result is an infographic
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...Matt Harrison
Python makes data science easy. In this deck we walk through a complete example of creating and evaluating a predictive model using Decision Trees and Random Forests. All of the code is included in the slides.
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
Автор доклада: Александр Сапронов.
Обзорный мини-доклад. В докладе вы найдете причину релиза 2.7.11 и новинки Python 3.5
Доклад сделан на 2 встрече сообщества PyNSK
Apple's Swift has achieved the top place in Stack Overflow's "Most Loved" list of programming languages in its 2015 Developer Survey. Based on information gleaned from GitHub and Stack Overflow, analyst firm RedMonk has seen Swift's popularity ranking soar from 68 to 22 in an unprecedented 6 months.
The "Extreme Swift" event does not require advanced, or even any, knowledge of Swift. Learn about some of the more outrageous features of the language which help explain what the fuss is all about!
Never look at programming the same way again — even if you never end up writing a single line of Swift code in your life.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
Inspired by Josh Bloch's Java Puzzlers, we put together our own Python Puzzlers. This slide deck brings you a set of 10 python puzzlers, that are fun and educational. Each puzzler will show you a piece of python code. Your task if to figure out what happens when the code is run. Whether you're a python beginner or a passionate python veteran, we hope that there's something to learn for everybody.
This slide deck was first presented at shopkick. Nandan Sawant and Ryan Rueth are engineers at shopkick. Keeping the audience in mind, most of the puzzlers are based on python 2.x.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Characteristics of Java and basic programming constructs like Data types, Variables, Operators, Control Statements, Arrays are discussed with relevant examples
Following a game show format made popular by Joshua Bloch and Neal Gafter's Java Puzzlers this presentation intends to both entertain and inform. Snippets of Python code the whose behaviour is not entirely obvious are shown, the audience will then be asked to pick from a number of options what the behaviour of the program is. The correct and sometimes non-intuitive answer will then be given along with a brief explanation of the idea the puzzle exposes. Only a modest working knowledge of the Python language is required to understand the puzzles, but the puzzles may also entertain the more experienced Python programmer.
These are the slides of the second part of this multi-part series, from Learn Python Den Haag meetup group. It covers List comprehensions, Dictionary comprehensions and functions.
Курс "Программирование на Java". Лекция 07 "Бонус - Головоломки".
Java Puzzlers. Синхронизация и многопоточность. Примитивы. Объекты и классы. Исключения и финализация.
МФТИ, 2016 год. Лектор - Лаврентьев Федор Сергеевич
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
I gave this presentation at Code Camp. As a data scientist and backcountry skier, I was interested in looking at fatal avalanche data. This covers scraping the data, analysis with Python, pandas and IPython Notebook. The final result is an infographic
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...Matt Harrison
Python makes data science easy. In this deck we walk through a complete example of creating and evaluating a predictive model using Decision Trees and Random Forests. All of the code is included in the slides.
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
Автор доклада: Александр Сапронов.
Обзорный мини-доклад. В докладе вы найдете причину релиза 2.7.11 и новинки Python 3.5
Доклад сделан на 2 встрече сообщества PyNSK
Apple's Swift has achieved the top place in Stack Overflow's "Most Loved" list of programming languages in its 2015 Developer Survey. Based on information gleaned from GitHub and Stack Overflow, analyst firm RedMonk has seen Swift's popularity ranking soar from 68 to 22 in an unprecedented 6 months.
The "Extreme Swift" event does not require advanced, or even any, knowledge of Swift. Learn about some of the more outrageous features of the language which help explain what the fuss is all about!
Never look at programming the same way again — even if you never end up writing a single line of Swift code in your life.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
These are the outline slides that I used for the Pune Clojure Course.
The slides may not be much useful standalone, but I have uploaded them for reference.
Toastmasters Pathways has 10 paths of 5 levels each. This powerpoint pivots on the catalog listing the contents of each path. http://d57tm.org/wp-content/uploads/2016/11/Pathways-Paths-and-Projects-Catalog-V2.1.pdf (George Marshall gave me the ok to share/post my view of his document)
This Java 9 presentation is from Spring Days NY 2017. It covers what is new in Java 9 aside from modules/lambdas. It also gives an update on the current state of lambdas
How to study for the Java Certification (and certifications in general) - given at 2016 FIRST robotics championship conference to 150-200 people. Mostly teenagers.
An overview of the Java OCA/OCP certifications with an emphasis on the major steps for how to study. Most of the content applies to any exam you could take. The examples are Java.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
1. Java 8 Hands on Workshop
FIRST Robotics Training
July 12, 2017
Jeanne Boyarsky
Twitter @jeanneboyarsky
Blog: http://www.selikoff.net
2. Disclaimer: Some of this material is copyright of Jeanne
Boyarsky, Scott Selikoff and/or Wiley Publishing
Twitter: @jeanneboyarsky
This PowerPoint is part of a hands
on workshop for teaching fluency
with Java 8 stream basics.
3. Twitter: @jeanneboyarsky
Pre-req:
Basic Java knowledge is required. If you can
implement this method using a loop, you
are good:
public int countStringsThatAreFourChars(
List<String> list) {
}
5. Twitter: @jeanneboyarsky
TryYourIde.java
(5 mins)
• Local IDE
or
• https://www.compilejava.net
https://github.com/boyarsky/java-8-
streams-by-puzzles
Run src/TryYourIde class
Prints Do stuff and Do more stuff
9. Java 8 Lambda Syntax Rules
Must have parens
unless exactly one
parameter
If listing type, must
be consistent
If multiple
statements: requires
braces, return and
semicolon
Twitter: @jeanneboyarsky
• () -> true
• a -> a.startsWith("test")
• (String a) ->
a.startsWith("test")
• (a, b) ->
a.startsWith("test")
• (String a, String b) ->
{ return
a.startsWith("test"); }
10. What’s wrong?
Twitter: @jeanneboyarsky
• a, b -> a.startsWith("test")
• a -> { a.startsWith("test"); }
• a -> { return a.startsWith("test") }
• (String a, b) -> a.startsWith("test")
• -> a.startsWith("test”)
11. Using variables
interface Gorilla { String move(); }
class GorillaFamily {
String walk = "walk";
void everyonePlay(boolean baby) {
String approach = "amble";
//approach = "run";
play(() -> walk);
play(() -> baby ? "hitch a ride" : "run");
play(() -> approach);
}
void play(Gorilla g) {
g.move();
}
}
1) Instance var
2) Class var
3) Effectively final
method param
or local var
Twitter: @jeanneboyarsky
12. LambdaFillInTheBlanks.java
(10-15 mins)
Easy - Fill in the blank so prints
out the numbers less than 3:
Stream.of(1, 2, 3, 5, 8)
.filter(__________)
.forEach(System.out::println);
Easy - Fill in the blank so prints out the
animals that are 4 characters in length:
Stream.of("cat", "dot", "fish", "rabbit")
.filter((p) -> { ___________ })
.forEach(System.out::println);
Medium - Fill in the blank so
prints the number 1:
long count = Stream.of(
"IBM", "Oracle", "Pivotal")
.filter(___________________)
.count();
System.out.println(count);
Twitter: @jeanneboyarsky
Challenge - How many
ways can you write a
lambda that takes one
String parameter named
“s” and returns the result of
s.isEmpty()?
16. FunctionalInterfacesFillInTheBlanks.java
(10-15 mins)
Twitter: @jeanneboyarsky
Easy: Predicate<String> p = s -> s.isEmpty();
Easy: Function<String, Integer> f = ________________;
Medium: Consumer<Double> c = ________________;
Hard: Supplier<Integer> s = _______________;
Challenge: How many ways can you fill in this blank?
_____________ ex = x -> "".equals(x.get(0));
17. Parts of a Stream Pipeline
Twitter: @jeanneboyarsky
18. Example of a Stream Pipeline
Twitter: @jeanneboyarsky
19. List<String> filtered = new ArrayList<>();
for (String name : list) {
if (name.length() == 4)
filtered.add(name);
}
Collections.sort(filtered);
List<String> result = filtered.subList(0, 2);
for (String name : result)
System.out.println(name);
Comparing code
list.stream()
.filter(n -> n.length() == 4)
.sorted().limit(2)
.forEach(System.out::println);
Twitter: @jeanneboyarsky
25. Puzzle – No Intermediate Operations
(10 mins)
Twitter: @jeanneboyarsky
Easy:
Using the puzzle 1 handouts, arrange so the code
prints
true true 3
boolean b1 = ______.___________;
boolean b2 = ________.__________;
long l = ________.________;
System.out.println(b1 + " " + b2 + " " + l);
26. TranslateSearch.java
(5-10 mins)
Twitter: @jeanneboyarsky
Easy:
Translate this method to a one liner using
streams and lambdas:
private static boolean isZeroInList(
List<BigDecimal> list) {
for (BigDecimal decimal : list) {
if (decimal.equals(BigDecimal.ZERO))
return true;
}
return false;
}
Medium: How might you format the code to make it
easier to read?
28. Puzzle – Intermediate Operations
(10 mins)
Twitter: @jeanneboyarsky
Medium:
Using the puzzle 2 handouts, arrange so the
code prints: true false 3
UnaryOperator<Integer> op = x -> x + 1;
Predicate<Integer> pred = x -> x > 5;
boolean b1 = Stream.iterate(1, op). ______. ______;
boolean b2 = Stream.iterate(1, op)
. ______. ______. ______;
long l = Stream.generate(() -> 1). ______. ______;
System.out.println(b1 + " " + b2 + " " + l);
Challenge: Why are there two correct answers?
29. CountMatches.java
(10-15 mins)
Twitter: @jeanneboyarsky
Easy:
Translate this method to a one liner using
streams and lambdas: (expected output is 1 and 0)
private static long numberMatches(List<String> list) {
long count = 0;
for (String string : list) {
if (string.contains("g"))
count++;
}
return count;
}
Challenge: Refactor the code so you can pass the
lambda as a method parameter.
30. MoreLogic.java
(10 mins)
Twitter: @jeanneboyarsky
Medium:
Implement the method to print “walrus” using the logic
described:
public static void main(String[] args) {
List<String> matchingList = Arrays.asList(
"whale", "dolphin", "whale”, "manatee",
"orca", "walrus", "calf");
printMe(matchingList);
}
private static void printMe(List<String> list) {
// Print the third distinct element alphabetically
// that is over 4 characters long
}
Hard: Write “the old way”
37. Squares.java
(5-10 mins)
Twitter: @jeanneboyarsky
Easy:
Translate this method to a one liner using
streams and lambdas:
private static List<String> convert(List<Integer> list) {
List<String> result = new ArrayList<>();
for (Integer number : list) {
if (number % 2 == 0)
result.add(number + "*" + number + "=" + (number *
number));
}
return result;
}
Challenge: Can you figure out how to make the return
type a LinkedList?
38. OddsAndEvens.java
(10 mins)
Twitter: @jeanneboyarsky
Medium:
Implement this method using streams and lambdas.
(Remember % is the modulus operator).
public static void main(String[] args) {
System.out.println(split(Arrays.asList(1, 4, 8,
13)));
System.out.println(split(Arrays.asList(1, 3)));
}
private static
Map<Boolean,List<Integer>> split(List<Integer> list) {
// partition the list into odds and evens
}
Hard: Change partioningBy to groupingBy. What’s the
difference?
Challenge: Implement this method without streams.
39. Method References
Infer lambdas by passing parameters for:
• Static methods
• Constructors
• Instance methods on the lambda param
• Instance methods on a particular instance
Twitter: @jeanneboyarsky
40. Static References
Twitter: @jeanneboyarsky
Java 7 new Consumer<List<Integer>>() {
public void accept(List<Integer> l) {
Collections.sort(l);
}
}
Lambda
l -> Collections.sort(l)
Method Reference
Collections::sort;
41. Constructor References
Twitter: @jeanneboyarsky
Java 7 new Supplier<ArrayList>() {
public ArrayList get() {
return new ArrayList();
}
}
Lambda
() -> new ArrayList()
Method Reference
ArrayList::new
Note: passing “zero length param list
44. MethodReferencesFillInTheBlanks.java
(10-15 mins)
Easy: Fill in the blank to print with a lambda and method
reference.
Stream.of(“", "b", ”bc”).forEach(_________);
Hard: How many of these can you use a method
reference to fill in the blank? (the string is empty, the
string is not empty, the string ends with ‘c’)
Stream.of(“", "b", ”bc").filter(_________)
.forEach(System.out::println);
Twitter: @jeanneboyarsky
45. Next Steps to Learn
• Primitive streams
• Reduce()
• Summary Statistics
• Advanced collect()
Twitter: @jeanneboyarsky
Key points
Quick preview of streams
Syntax and flow will come naturally by the end of the session
Note that Java and Groovy use similar but different syntax/method names (aka be careful if primarily a Groovy developer)
Not expected to understand the details/syntax
Appreciate that there isn’t a loop or if statement. Just the declarative statements.
Goal of this “slide” is to ensure all attendees are able to run a Java 8 program – either in their local IDE or online.
Online IDEs:
compilejava.net – easiest to use – make sure not to have package names
ideone.com – has ads, remove public keyword from class to work
https://commons.wikimedia.org/wiki/File:Interactive_icon.svg
Image from https://commons.wikimedia.org/wiki/File:Gnome-edit-paste.svg
Answers:
Need parens since two parameters
Need return statement since braces
Need semi-colon since braces
Need type for neither or both params
Need parameter
https://goo.gl/images/5X5VL2
Answers:
Easy: n -&gt; n &lt; 3
Easy: return p.length() == 4;
Medium: There are many correct answers such as n -&gt; n.startsWith(&quot;I&quot;)
Challenge: I can think of 6 ways:
Predicate&lt;String&gt; p1 = s -&gt; s.isEmpty();
Predicate&lt;String&gt; p2 = (s) -&gt; s.isEmpty();
Predicate&lt;String&gt; p3 = (String s) -&gt; s.isEmpty();
Predicate&lt;String&gt; p4 = s -&gt; { return s.isEmpty(); };
Predicate&lt;String&gt; p5 = (s) -&gt; { return s.isEmpty(); };
Predicate&lt;String&gt; p6 = (String s) -&gt; { return s.isEmpty(); };
Key Points
Swimmer is a functional interface
Only one method and it is abstract
Slower is a functional interface
getCrawlSpeed() is abstract
toString() is not abstract because inherited from Object
getSlowestSpeed() and getFastestSpeed() are not abstract
Faster is not a functional interface
It has one abstract method declared but inherits another
Key points
Don’t need to memorize this.
Note that the common combinations exist.
If writing code that uses streams, you don’t actually need to know the functional interface name. Compiler infers it.
Do need to know these methods if writing libraries
Many answers such as:
Easy: s -&gt; s.isEmpty()
Easy: s -&gt; s.length()
Medium: d -&gt; System.out.println(d)
Hard: () -&gt; new Random().nextInt() or () -&gt; 1
Challenge: I can find six
Predicate&lt;List&lt;String&gt;&gt;
Function&lt;List&lt;String&gt;, Boolean&gt;
Consumer&lt;List&lt;String&gt;&gt;
Predicate&lt;Map&lt;Integer, String&gt;&gt;
Function&lt;Map&lt;Integer, String&gt;, Boolean&gt;
Consumer&lt;Map&lt;Integer, String&gt;&gt;
Go over the three parts of a stream pipeline
Walk through the factory example
Compare loop to lambda code
Map the previous example to the three parts of a pipeline
Answers:
If no source, can’t start
If not intermediate operations ok.
If no terminal operations, the stream isn’t run.
Answer:
Using the puzzle 1 handouts, arrange so the code prints
true true 3
boolean b1 = Stream.empty().allMatch(p -&gt; true);
boolean b2 = Stream.generate(String::new).anyMatch(p -&gt; true);
long l = Stream.of(1,2,3).count();
System.out.println(b1 + &quot; &quot; + b2 + &quot; &quot; + l);
Or
boolean b1 = Stream.generate(String::new).anyMatch(p -&gt; true);
boolean b2 = Stream.empty().allMatch(p -&gt; true);
long l = Stream.of(1,2,3).count();
System.out.println(b1 + &quot; &quot; + b2 + &quot; &quot; + l);
Answer
Medium:
list.stream().filter(s -&gt; s.length() &gt; 4)
.sorted()
.distinct()
.skip(2)
.limit(1)
.forEach(n -&gt; System.out.println(n));
Hard:
TreeSet&lt;String&gt; set = new TreeSet&lt;&gt;(list);
List&lt;String&gt; sortedList = new ArrayList&lt;&gt;();
for (String string : set) {
if (string.length() &gt; 4) {
sortedList.add(string);
}
}
System.out.println(sortedList.get(2));
Answer:
Optional&lt;Integer&gt; o1 = Stream.generate(() -&gt; 1).findAny();
Optional&lt;Integer&gt; o2 = Stream.iterate(1, x -&gt; x + 1).map(x -&gt; x * 2).limit(3).max();
Optional&lt;Integer&gt; o3 = Stream.iterate(1, x -&gt; x + 1).limit(5).filter(x -&gt; x &gt; 8).findFirst();
Or
Optional&lt;Integer&gt; o1 = Stream.generate(() -&gt; 1).findFirst();
Optional&lt;Integer&gt; o2 = Stream.iterate(1, x -&gt; x + 1).map(x -&gt; x * 2).limit(3).max();
Optional&lt;Integer&gt; o3 = Stream.iterate(1, x -&gt; x + 1).limit(5).filter(x -&gt; x &gt; 8).findAny();
Or
Optional&lt;Integer&gt; o1 = Stream.generate(() -&gt; 1).findAny();
Optional&lt;Integer&gt; o2 = Stream.iterate(1, x -&gt; x + 1).limit(3).map(x -&gt; x * 2).max();
Optional&lt;Integer&gt; o3 = Stream.iterate(1, x -&gt; x + 1).limit(5).filter(x -&gt; x &gt; 8).findFirst();
Or
Optional&lt;Integer&gt; o1 = Stream.generate(() -&gt; 1).findFirst();
Optional&lt;Integer&gt; o2 = Stream.iterate(1, x -&gt; x + 1).limit(3). map(x -&gt; x * 2).max();
Optional&lt;Integer&gt; o3 = Stream.iterate(1, x -&gt; x + 1).limit(5).filter(x -&gt; x &gt; 8).findAny();
For the first line, findAny() or findFirst() give the same result because all the entries are 1. For the last line, either gives the same result because the stream is empty at that point.
Also, the order of map and limit doesn’t matter since they don’t interrelate.
System.out.println(o1.orElse(-1) + &quot; &quot; + o2.orElse(-1) + &quot; &quot; + o3.orElse(-1));
Answer:
return list.stream()
.filter(n -&gt; n%2 ==0)
.map(n -&gt; n + &quot;*&quot; + n + &quot;=&quot; + (n*n))
.collect(Collectors.toList());
Challenge answer:
return list.stream()
.filter(n -&gt; n%2 ==0)
.map(n -&gt; n + &quot;*&quot; + n + &quot;=&quot; + (n*n))
.collect(Collectors.toCollection(LinkedList::new));
Answer
Easy:
return list.stream().collect(Collectors.partitioningBy(x -&gt; x % 2 == 0));
Hard:
Grouping by doesn’t include the key if there are no matches
Challenge:
Map&lt;Boolean,List&lt;Integer&gt;&gt; result = new HashMap&lt;&gt;();
result.put(Boolean.FALSE, new ArrayList&lt;&gt;());
result.put(Boolean.TRUE, new ArrayList&lt;&gt;());
for (Integer integer : list) {
boolean key = integer %2 == 0;
result.get(key).add(integer);
}
return result;
Answers:
Easy: System.out::println and x -&gt; System.out.println(x)
Hard: One
Stream.of(&quot;&quot;, &quot;b&quot;, &quot;bc&quot;).filter(String::isEmpty).forEach(System.out::println);
String is not empty requires a lambda (or you to write a static method) because it uses an operator
String ends with ‘c’ requires a lambda (or you to write a static method) because it uses a parameter