In this presentation we introduce Java 8’s main new features and show how you can benefit from them to write code that is more readable and more flexible to requirement changes.
We will show how:
1) Lambda expressions and behaviour parameterisation let you write concise code that can cope for requirement changes
2) The new Streams API lets you express complex data process queries in a succinct way while automatically leveraging your multi-core architecture
3) Using the new Optional class can let you reduce unexpected NullPointer exceptions
4) Default methods bring a form of multi-inheritance to Java
PuppetConf 2017: Hiera 5: The Full Data Enchilada- Hendrik Lindberg, PuppetPuppet
Separating data from code is just as important as it has always been for creating reusable code that can be conveniently configured for different situations. This has been possible to do in Puppet for quite some time, using Hiera and automatic parameter lookup. The new release of Hiera 5, introduced late in the Puppet 4.x series, brings new capabilities for data management. Data is no longer just global — it can be defined in an environment and inside a module. Plus, data integration no longer requires special backends — the point of integration is now a function. There are also new ways to reference data files. And there's so much more in Hiera 5. This talk introduces all the features of Hiera 5 now available in Puppet 5, and shows how they can be used. Integrators who want to write their own backends will also learn how to do that.
PuppetConf 2017: Hiera 5: The Full Data Enchilada- Hendrik Lindberg, PuppetPuppet
Separating data from code is just as important as it has always been for creating reusable code that can be conveniently configured for different situations. This has been possible to do in Puppet for quite some time, using Hiera and automatic parameter lookup. The new release of Hiera 5, introduced late in the Puppet 4.x series, brings new capabilities for data management. Data is no longer just global — it can be defined in an environment and inside a module. Plus, data integration no longer requires special backends — the point of integration is now a function. There are also new ways to reference data files. And there's so much more in Hiera 5. This talk introduces all the features of Hiera 5 now available in Puppet 5, and shows how they can be used. Integrators who want to write their own backends will also learn how to do that.
The slides of my talk at Devoxx BE 2017. This in depth talk is all about collectors: those available, because we need to know them, those that we can create, those we had no idea they could be created, and the others, as there is in fact no limit to what can be done with this API. The concept of downstream collector will be used to show how we can write entire data processing pipelines using collectors only, and pass them as parameters to other pipelines.
Don't optimize my queries, organize my data!Julian Hyde
Your queries won't run fast if your data is not organized right. Apache Calcite optimizes queries, but can we make it optimize data? We had to solve several challenges. Users are too busy to tell us the structure of their database, and the query load changes daily, so Calcite has to learn and adapt. We talk about new algorithms we developed for gathering statistics on massive database, and how we infer and evolve the data model based on the queries.
A talk given by Julian Hyde at DataEngConf SF on April 17th 2018.
Did you know that databases often “cheat”? Even with a scalable query engine and smart optimizer, many real-world queries would be too slow if the engine read all the data, so the engine re-writes your query to use a pre-materialized result. B-tree indexes made the first relational databases possible, and there are now many flavors of materialization, from explicit materialized views to OLAP-style caching and spatial indexes. Materialization is more relevant than ever in today’s heterogenous, distributed systems.
If you are evaluating data engines, we describe what materialization features to look for in your next engine. If you are implementing an engine, we describe the features provided by Apache Calcite to design, maintain and use materializations.
Java Collections Framework Inroduction with Video TutorialMarcus Biel
This presentation is part of my free Java 8 course focusing on clean code principles. In this piece, you will be given a high-level introduction of the Java Collections Framework (JCF).
You can find the full article with lots of other additional materials here -
http://www.marcus-biel.com/java-collections-framework/
A talk given by Julian Hyde at FlinkForward, Berlin, on 2016/09/12.
Streaming is necessary to handle data rates and latency, but SQL is unquestionably the lingua franca of data. Is it possible to combine SQL with streaming, and if so, what does the resulting language look like? Apache Calcite is extending SQL to include streaming, and Apache Flink is using Calcite to support both regular and streaming SQL. In this talk, Julian Hyde describes streaming SQL in detail and shows how you can use streaming SQL in your application. He also describes how Calcite’s planner optimizes queries for throughput and latency.
Kotlin decoration - February Berlin Kotlin MeetupSinan KOZAK
Wouldnt it be nice to delegate repeating things and just focus on the parts that make the difference?
We all prefer composition over inheritance, but Java doesn’t help us with all the inheritance it has.
Kotlin has convenient solutions to create reusable code with delegation.
Besides the obvious benefit of delegation, there are ways to trick compiler and have better code separation.
Exploring type level programming in ScalaJorge Vásquez
In this introduction to type-level programming in Scala, we are going to discuss how we can leverage the full power of the type system to verify domain properties of an application at compile-time, instead of doing runtime verifications at the value-level
The workshop aims to introduce Scala > 2.10 and was held at Clueda AG .
It gives an introduction to Scala also explaining widely used language features like case classes, patten matching, futures and string interpolation.
The slides of my talk at Devoxx BE 2017. This in depth talk is all about collectors: those available, because we need to know them, those that we can create, those we had no idea they could be created, and the others, as there is in fact no limit to what can be done with this API. The concept of downstream collector will be used to show how we can write entire data processing pipelines using collectors only, and pass them as parameters to other pipelines.
Don't optimize my queries, organize my data!Julian Hyde
Your queries won't run fast if your data is not organized right. Apache Calcite optimizes queries, but can we make it optimize data? We had to solve several challenges. Users are too busy to tell us the structure of their database, and the query load changes daily, so Calcite has to learn and adapt. We talk about new algorithms we developed for gathering statistics on massive database, and how we infer and evolve the data model based on the queries.
A talk given by Julian Hyde at DataEngConf SF on April 17th 2018.
Did you know that databases often “cheat”? Even with a scalable query engine and smart optimizer, many real-world queries would be too slow if the engine read all the data, so the engine re-writes your query to use a pre-materialized result. B-tree indexes made the first relational databases possible, and there are now many flavors of materialization, from explicit materialized views to OLAP-style caching and spatial indexes. Materialization is more relevant than ever in today’s heterogenous, distributed systems.
If you are evaluating data engines, we describe what materialization features to look for in your next engine. If you are implementing an engine, we describe the features provided by Apache Calcite to design, maintain and use materializations.
Java Collections Framework Inroduction with Video TutorialMarcus Biel
This presentation is part of my free Java 8 course focusing on clean code principles. In this piece, you will be given a high-level introduction of the Java Collections Framework (JCF).
You can find the full article with lots of other additional materials here -
http://www.marcus-biel.com/java-collections-framework/
A talk given by Julian Hyde at FlinkForward, Berlin, on 2016/09/12.
Streaming is necessary to handle data rates and latency, but SQL is unquestionably the lingua franca of data. Is it possible to combine SQL with streaming, and if so, what does the resulting language look like? Apache Calcite is extending SQL to include streaming, and Apache Flink is using Calcite to support both regular and streaming SQL. In this talk, Julian Hyde describes streaming SQL in detail and shows how you can use streaming SQL in your application. He also describes how Calcite’s planner optimizes queries for throughput and latency.
Kotlin decoration - February Berlin Kotlin MeetupSinan KOZAK
Wouldnt it be nice to delegate repeating things and just focus on the parts that make the difference?
We all prefer composition over inheritance, but Java doesn’t help us with all the inheritance it has.
Kotlin has convenient solutions to create reusable code with delegation.
Besides the obvious benefit of delegation, there are ways to trick compiler and have better code separation.
Exploring type level programming in ScalaJorge Vásquez
In this introduction to type-level programming in Scala, we are going to discuss how we can leverage the full power of the type system to verify domain properties of an application at compile-time, instead of doing runtime verifications at the value-level
The workshop aims to introduce Scala > 2.10 and was held at Clueda AG .
It gives an introduction to Scala also explaining widely used language features like case classes, patten matching, futures and string interpolation.
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
This presentation provides a comprehensive overview of modern programming in Java. It focuses only on Java 8 features: Lambdas, Streams and Date Time API. It also briefly covers refactoring legacy Java code to Java 8.
Gdg almaty. Функциональное программирование в Java 8Madina Kamzina
О функциональном программировании (ФП), преимуществах его использования и о том, какие возможности для него добавили в новом релизе Java. Слушатели также узнают, почему уже сейчас стоит начать изучать ФП.
Митап состоялся ->> https://plus.google.com/u/0/b/100893943920756626864/events/c0b2b1ih9ft0opcdnmdgp3453rk
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
The programming world is moving towards functional programming. All the major and popular programming languages (including Java, C++, C#, Swift, and Python) support functional programming. Functional programming languages such as Clojure, Scala, and F# are on the rise. This talk introduces functional programming to those who are new to this paradigm using lambda functions in Java 8. The talk will cover syntax and semantics of lambda functions, moving from external iteration to internal iteration, and how lambda functions can result in shorter and more readable code. If you are new to functional programming and want productivity gains from using Java’s lambda functions, this talk is certainly for you.
Functional Programming With Lambdas and Streams in JDK8IndicThreads
The significant new language feature in Java SE 8 is the introduction of Lambda expressions, a way of defining and using anonymous functions. On its own this provides a great way to simplify situations where we would typically use an inner class today. However, Java SE 8 also introduces a range of new classes in the standard libraries that are designed specifically to take advantage of Lambdas. These are primarily included in two new packages: java.util.stream and java.util.function.
After a brief discussion of the syntax and use of Lambda expressions this session will focus on how to use Streams to greatly simplify the way bulk and aggregate operations are handled in Java. We will look at examples of how a more functional approach can be taken in Java using sources, intermediate operations and terminators. We will also discuss how this can lead to improvements in performance for many operations through the lazy evaluation of Streams and how code can easily be made parallel by changing the way the Stream is created.
Session at the IndicThreads.com Confence held in Pune, India on 27-28 Feb 2015
http://www.indicthreads.com
http://pune15.indicthreads.com
What you need to know about Lambdas - Jamie Allenjaxconf
Lambdas are coming to the Java language in the upcoming release of Java 8! While this is generally great news, many Java developers have never experienced lambdas before, and may not realize the costs and pitfalls associated with this style of programming. In this talk, we will discuss the many issues of using Lambdas in Java as well as Scala, and measures we can talk to avoid them. We will also review concepts associated with lambdas to make sure everyone is on the same page, such as closures, higher order functions and Eta Expansion.
Presentation on the new features introduced in JDK 8, presented on the 26.02.2013 in Sofia University in front of students and members of the Bulgarian java user group.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
4. Java
8
in
Ac$on:
Lambdas,
Streams
and
func$onal-‐style
programming
4
• Co-‐authored
with
Mario
Fusco
&
Alan
Mycro`
• Most
complete
book
on
Java
8
h"p://manning.com/urma
5. Why
Java
8
Before:
Collec$ons.sort(inventory,
new
Comparator<Apple>()
{
public
int
compare(Apple
a1,
Apple
a2){
return
a1.getWeight().compareTo(a2.getWeight());
}
});
A5er:
inventory.sort(comparing(Apple::getWeight));
5
6. Why
Java
8?
6
List<Dish>
lowCaloricDishes
=
new
ArrayList<>();
for(Dish
d:
dishes){
if(d.getCalories()
<
400){
lowCaloricDishes.add(d);
}
}
List<String>
lowCaloricDishesName
=
new
ArrayList<>();
Collec$ons.sort(lowCaloricDishes
,
new
Comparator<Dish>()
{
public
int
compare(Dish
d1,
Dish
d2){
return
Integer.compare(d1.getCalories(),
d2.getCalories());
}
});
for(Dish
d:
lowCaloricDishes){
lowCaloricDishesName.add(d.getName());
}
6
sor$ng
by
calories
filtering
low
calories
Extract
names
8. Why
Java
8?
(
as
seen
by
language
designers)
• Commodity
CPUs
are
mul$core
(e.g.
4
cores)
• Analogy:
you
have
4
assistants,
in
theory
you
could
get
the
work
done
4
$mes
faster!
• In
prac$ce:
– it’s
hard
because
you
now
have
to
figure
out
how
to
distribute
a
piece
of
work
amongst
4
people.
– It’s
easier
to
just
pass
the
whole
piece
of
work
to
one
person.
8
9. Why
Java
8?
(
as
seen
by
language
designers)
• Vast
majority
of
Java
programs
use
only
one
of
these
cores
and
leave
the
others
idle
• Why?
wri$ng
efficient
parallel
code
is
hard
– summing
an
array
with
a
for
loop
is
easy
– how
to
sum
an
array
on
4
cores?
9
10. Why
Java
8?
(
as
seen
by
language
designers)
• Java
8
introduces
features
that
make
parallel
data
processing
easier
• Driven
from
three
concepts:
– stream
processing
– behaviour
parameterisa$on
("passing
code")
– no
shared
mutable
data
10
15. No
shared
mutable
data
List<String>
lowCaloricDishesName
=
dishes.parallelStream()
.filter(d
-‐>
d.getCalories()
<
400)
.sorted(comparing(Dish::getCalories))
.map(Dish::getName)
.collect(toList());
15
Can
be
duplicated
and
ran
on
disjoint
part
of
input
16. Java
8
• Introduces
a
concise
way
to
pass
behaviour
– lambda
expressions,
method
references
• Introduces
an
API
to
process
data
in
parallel
– Streams
API
– several
opera$ons
such
as
filter,
map,
reduce
can
be
parameterised
with
lambdas
• Also:
default
methods
(more
later)
– more
flexible
inheritance
16
17. Behaviour
parameterisa$on
• Goal:
abstract
over
behaviour
– Do
<something>
for
every
element
in
a
list
– Do
<something>
else
when
the
list
is
finished
–
Do
<yet
something
else>
if
an
error
occurs
• Why
should
you
care?
– Adapt
to
changing
requirements
– Java
8
Streams
API
heavily
relies
on
it
17
18. 1st
awempt:
fitering
green
apples
public
sta$c
List<Apple>
filterGreenApples(List<Apple>
inventory)
{
List<Apple>
result
=
new
ArrayList<>();
for(Apple
apple:
inventory){
if("green".equals(apple.getColor()
)
{
result.add(apple);
}
}
return
result;
}
18
19. 2nd
awempt:
abstrac$ng
color
public
sta$c
List<Apple>
filterApplesByColour(List<Apple>
inventory,
String
color)
{
List<Apple>
result
=
new
ArrayList<>();
for
(Apple
apple:
inventory){
if
(apple.getColor().equals(color)))
{
result.add(apple);
}
}
return
result;
}
19
List<Apple>
greenApples
=
filterApplesByColor(inventory,
"green");
List<Apple>
redApples
=
filterApplesByColor(inventory,
"red");
20. 2nd
awempt:
abstrac$ng
weight
public
sta$c
List<Apple>
filterApplesByWeight(List<Apple>
inventory,
int
weight)
{
List<Apple>
result
=
new
ArrayList<>();
for
(Apple
apple:
inventory){
if
(apple.getWeight()
>
weight)
{
result.add(apple);
}
}
return
result;
}
20
List<Apple>
heavyApples
=
filterApplesByWeight(inventory,
150);
List<Apple>
megaHeavyApples
=
filterApplesByWeight(inventory,
250);
21. 3rd
awempt:
filtering
with
everything
public
sta$c
List<Apple>
filter
(List<Apple>
inventory,
String
color,
int
weight,
boolean
flag)
{
List<Apple>
result
=
new
ArrayList<>();
for
(Apple
apple:
inventory){
if
(
(flag
&&
apple.getColor().equals(color))
||
(!flag
&&
apple.getWeight()
>
weight)
){
result.add(apple);
}
}
return
result;
}
21
List<Apple>
greenApples
=
filter(inventory,
"green",
0,
true);
List<Apple>
heavyApples
=
filter(inventory,
"",
150,
false);
22. 4th
(a)
awempt:
modeling
selec$on
criteria
public
interface
ApplePredicate{
public
boolean
test
(Apple
apple);
}
public
class
AppleWeightPredicate
implements
ApplePredicate{
public
boolean
test(Apple
apple){
return
apple.getWeight()
>
150;
}
}
public
class
AppleColorPredicate
implements
ApplePredicate{
public
boolean
test(Apple
apple){
return
"green".equals(apple.getColor());
}
}
22
24. 4th
(b)
awempt:
filtering
by
an
abstract
criteria
public
sta$c
List<Apple>
filter(List<Apple>
inventory,
ApplePredicate
p){
List<Apple>
result
=
new
ArrayList<>();
for(Apple
apple:
inventory){
if(p.test(apple)){
result.add(apple);
}
}
return
result;
}
24
25. Let’s
pause
for
a
liwle
bit
• Our
code
is
much
more
flexible!
– can
create
any
kinds
of
selec$on
criteria
on
an
Apple
– re-‐use
of
code
for
filter
• However,
declaring
many
selec$on
criterias
using
classes
is
verbose…
L
– we
have
the
right
abstrac$on
but
not
good
concision
– we
need
a
bewer
way
to
create
and
pass
behaviours
25
26. 5th
awempt:
anonymous
classes
List<Apple>
result
=
filter(inventory,
new
ApplePredicate()
{
public
boolean
test(Apple
apple){
return
"red".equals.(apple.getColor());
}
});
List<Apple>
result
=
filter(inventory,
new
ApplePredicate()
{
public
boolean
test(Apple
apple){
return
apple.getWeight()
>
150;
}
});
26
27. 6th
awempt:
Java
8
lambdas
List<Apple>
result
=
filter(inventory,
(Apple
apple)
-‐>
"red".equals.(apple.getColor()));
List<Apple>
result
=
filter(inventory,
(Apple
apple)
-‐>
apple.getWeight()
>
150);
27
Great
because
closer
to
problem
statement!
28. 7th
awempt:
abstrac$ng
over
the
list
type
public
sta$c
<T>
List<T>
filter
(List<T>
list,
Predicate<T>
p)
{
List<T>
result
=
new
ArrayList<>();
for(T
e:
list){
if(p.test(e))
{
result.add(e);
}
}
return
result;
}
28
29. 8th
awempt:
Java
8
lambdas
again
List<String>
result
=
filter(strings,
(String
s)
-‐>
s.endsWith("JDK"));
List<Integer>
result
=
filter(numbers,
(Integer
i)
-‐>
i
%
2
==
0);
List<Apple>
result
=
filter(inventory,
(Apple
a)
-‐>
apple.getWeight()
>
150);
29
30. Moral
of
the
story
• Behaviour
parameterisa$on
lets
you
write
more
flexible
code
– Adapt
for
changes
– Avoids
code
duplica$on
• To
encourage
this
style
of
programming
we
need
a
concise
way
to
create
and
pass
behaviours
– Java
8
brings
lambda
expressions
to
help!
30
31. Flexible
Concise
Anonymous
classes
Verbose
Rigid
Lambdas
Class
+
Instance
Value
parameterisa$on
Behaviour
parameterisa$on
Value
vs
Behaviour
parameterisa$on
32. Lambda
expressions:
what
is
it?
• A
lambda
expression
is:
– a
kind
of
anonymous
func$on
– that
can
be
passed
around:
– It
doesn’t
have
a
name,
but
it
has
a
list
of
parameters,
a
body,
a
return
type,
and
also
possibly
a
list
of
excep$ons
that
can
be
thrown.
32
34. Lambda
expressions:
what
is
it?
• A
lambda
expression
is:
– a
kind
of
anonymous
func$on
• Anonymous:
doesn’t
have
an
explicit
name
like
a
method:
less
to
write
and
think
about!
• Func$on:
not
associated
to
a
class
like
a
method
is
34
35. Lambda
expressions:
what
is
it?
• A
lambda
expression
is:
– a
kind
of
anonymous
func$on
– that
can
be
passed
around:
• Passed
around:
A
lambda
expression
can
be
passed
as
argument
to
a
method
or
stored
in
a
variable
35
36. Lambda
expressions:
what
is
it?
• A
lambda
expression
is:
– a
kind
of
anonymous
func$on
– that
can
be
passed
around:
– it
doesn’t
have
a
name,
but
it
has
a
list
of
parameters,
a
body,
a
return
type,
and
also
possibly
a
list
of
excep$ons
that
can
be
thrown.
•
Concise:
you
don’t
need
to
write
a
lot
of
boilerplate
like
you
do
for
anonymous
classes.
36
37. Goal
• Goal:
let
you
pass
a
piece
of
behaviour/code
in
a
concise
way
• You
can
cope
with
changing
requirements
by
using
a
behaviour,
represented
by
a
lambda,
as
a
parameter
to
a
method
• You
no
longer
need
to
choose
between
abstracaon
and
concision!
37
38. Before/A`er
Before:
inventory.sort(new
Comparator<Apple>()
{
public
int
compare(Apple
a1,
Apple
a2){
return
a1.getWeight().compareTo(a2.getWeight());
}
});
A5er:
inventory.sort((Apple
a1,
Apple
a2)
-‐>
a1.getWeight().compareTo(a2.getWeight()));
38
39. Examples
39
Use
case
Example
of
lambda
A
boolean
expression
(List<String>
list)
-‐>
list.isEmpty()
Crea$ng
objects
()
-‐>
new
Apple(10)
Consuming
from
an
object
(Apple
a)
-‐>
System.out.println(a.getWeight())
Select/extract
from
an
object
(String
s)
-‐>
s.length()
Combine
two
values
(int
a,
int
b)
-‐>
a
*
b
Compare
two
objects
(Apple
a1,
Apple
a2)
-‐>
a1.getWeight().compareTo(a2.getWeight())
40. Where
and
how
to
use
lambdas?
40
• Java
lets
you
pass
expressions
only
where
a
type
is
expected
• So
what’s
the
type
of
a
lambda
expression?
41. Func$onal
interface
(1)
41
• The
type
of
a
lambda
expression
is
essen$ally
a
funcaonal
interface
• A
func$onal
interface
is
an
interface
that
declares
exactly
one
(abstract)
method.
42. Func$onal
interface
(2)
42
//
java.u$l.Comparator
public
interface
Comparator<T>
{
public
int
compare(T
o1,
T
o2);
}
public
interface
Runnable
{
public
void
run();
}
public
interface
ApplePredicate
{
public
boolean
test
(Apple
a);
}
43. Func$onal
interface
&
Lambdas
43
• The
signature
of
the
abstract
method
of
the
func$onal
interface
essen$ally
describes
the
signature
of
the
lambda
expression.
• Lambda
expressions
let
you
provide
the
implementa$on
of
the
abstract
method
of
a
func$onal
interface
directly
inline
and
treat
the
whole
expression
as
an
instance
of
a
func$onal
interface.
44. Func$onal
interface
&
Lambdas
44
Runnable
r1
=
()
-‐>
System.out.println("Hello
World
1");
Runnable
r2
=
new
Runnable(){
public
void
run(){
System.out.println("Hello
World
2");
}
}
public
void
process(Runnable
r){
r.run();
}
process(r1);
process(r2);
process(()
-‐>
System.out.println("Hello
World
3"));
46. Execute
Around
Pawern
46
public
sta$c
String
processFile()
throws
IOExcep$on
{
try
(BufferedReader
br
=
new
BufferedReader(new
FileReader("data.txt")))
{
return
br.readLine();
}
}
• This
current
code
is
limited.
You
can
read
only
the
first
line
of
the
file.
47. What
we
want
47
String
result
=
processFile((BufferedReader
br)
-‐>
br.readLine());
String
result
=
processFile((BufferedReader
br)
-‐>
br.readLine()
+
br.readLine());
48. Step
1:
Introducing
func$onal
interface
48
public
interface
BufferedReaderProcessor
{
public
String
process(BufferedReader
b)
throws
IOExcep$on;
}
public
sta$c
String
processFile(BufferedReaderProcessor
p)
throws
IOExcep$on
{
...
}
49. Step
2:
Execu$ng
a
behaviour
49
public
sta$c
String
processFile(BufferedReaderProcessor
p)
throws
IOExcep$on
{
try
(BufferedReader
br
=
new
BufferedReader(new
FileReader("data.txt")))
{
return
p.process(br);
}
}
String
result
=
processFile((BufferedReader
br)
-‐>
br.readLine());
String
result
=
processFile((BufferedReader
br)
-‐>
br.readLine()
+
br.readLine());
50. Lots
of
func$onal
interfaces
50
Funcaonal
interface
Lambda
signature
Predicate<T>
T
-‐>
boolean
Consumer<T>
T
-‐>
void
Func$on<T,
R>
T
-‐>
R
Supplier<T>
()
-‐>
T
UnaryOperator<T>
T
-‐>
T
Binaryoperator<T>
(T,
T)
-‐>
T
BiFunc$on<T,
U,
R>
(T,
U)
-‐>
R
• Have
a
look
in
java.u$l.func$on.*
51. Method
references
51
• Method
references
let
you
reuse
exis$ng
method
defini$ons
and
pass
them
just
like
lambdas.
«
First-‐class
»
func$ons
• Just
a
syntac'c
suggar
to
lambdas
Before:
(Apple
a)
-‐>
a.getWeight()
A5er:
Apple::getWeight
Before:
(str,
i)
-‐>
str.substring(i)
A5er:
String::substring
53. Bewer
code
with
Java
8:
a
prac$cal
example
53
public
class
AppleComparator
implements
Comparator<Apple>
{
public
int
compare(Apple
a1,
Apple
a2){
return
a1.getWeight().compareTo(a2.getWeight());
}
}
inventory.sort(new
AppleComparator());
54. Anonymous
class
54
inventory.sort(new
Comparator<Apple>()
{
public
int
compare(Apple
a1,
Apple
a2){
return
a1.getWeight().compareTo(a2.getWeight());
}
});
59. Tidy
up
59
import
sta$c
java.u$l.Comparator.comparing;
inventory.sort(comparing(Apple::getWeight));
Reads
like
probable
statement!
60. Streams
60
• Nearly
every
Java
applica$ons
makes
and
processes
collec$ons
• However
processing
collec$ons
is
far
from
perfect:
– SQL
like
opera$ons?
– How
to
efficiently
process
large
collec$ons?
61. SQL-‐like
opera$ons
61
• Many
processing
pawerns
are
SQL-‐like
– finding
a
transac$on
with
highest
value
– grouping
transac$ons
related
to
grocery
shopping
• Re-‐implemented
every
$me
• SQL
is
declaraave
– express
what
you
expect
not
how
to
implement
a
query
– SELECT
id,
MAX(value)
from
transac$ons
62. Example:
Java
7
62
List<Transac$on>
groceryTransac$ons
=
new
Arraylist<>();
for(Transac$on
t:
transac$ons){
if(t.getType()
==
Transac$on.GROCERY){
groceryTransac$ons.add(t);
}
}
Collec$ons.sort(groceryTransac$ons,
new
Comparator(){
public
int
compare(Transac$on
t1,
Transac$on
t2){
return
t2.getValue().compareTo(t1.getValue());
}
});
List<Integer>
transac$onIds
=
new
ArrayList<>();
for(Transac$on
t:
groceryTransac$ons){
transac$onsIds.add(t.getId());
}
sor$ng
by
decreasing
value
filtering
grocery
transac$ons
extract
Ids
65. Ok
cool
–
so
what’s
a
Stream?
65
• Informal:
a
fancy
iterator
with
database-‐like
opera$ons
• Formal:
A
sequence
of
elements
from
a
source
that
supports
aggregate
opera$ons.
66. Ok
cool
–
so
what’s
a
Stream?
66
• Sequence
of
elements:
a
stream
provides
an
interface
to
a
sequenced
set
of
values
of
a
specific
element
type.
However,
streams
don’t
actually
store
elements,
they
are
computed
on
demand.
67. Ok
cool
–
so
what’s
a
Stream?
67
• Source:
Streams
consume
from
a
data-‐providing
source
such
as
Collec$ons,
Arrays,
or
IO
resources.
68. Ok
cool
–
so
what’s
a
Stream?
68
• Aggregate
operaaons:
Streams
support
SQL-‐like
opera$ons
and
common
opera$ons
from
func$onal
programing
languages
such
as
filter,
map,
reduce,
find,
match,
sorted
etc.
69. Two
addi$onal
proper$es
69
• Pipelining:
Many
stream
opera$ons
return
a
stream
themselves.
This
allows
opera$ons
to
be
chained
and
form
a
larger
pipeline
as
well
as
certain
op$misa$ons
(more
later).
• Internal
iteraaon:
In
contrast
to
collec$ons,
that
are
iterated
explicitly
(“external
itera$on”),
stream
opera$ons
do
the
itera$on
behind
the
scene
for
you.
70. 70
Pipelining
• Intermediate
operaaons:
return
a
Stream
and
can
be
“connected”
• Terminal
operaaons:
computes
the
result
of
the
pipeline
Intermediate
opera$ons
Terminal
opera$on
78. Streams:
much
more(3)
Map<Boolean,
Map<Dish.Type,
List<Dish>>>
vegetarianDishesByType
=
menu.stream().collect(
paraaoningBy(Dish::isVegetarian,
groupingBy(Dish::getType)));
• Produces
a
two-‐level
Map:
{false={FISH=[prawns,
salmon],
MEAT=[pork,
beef,
chicken]},
true={OTHER=[french
fries,
rice,
season
fruit,
pizza]}}
78
79. Step
1:
sequen$al
for
loop
public
sta$c
long
itera$veSum(long
n)
{
long
result
=
0;
for
(long
i
=
0;
i
<
n;
i++)
{
result
+=
i;
}
return
result;
}
79
3ms
80. Step
2:
sequen$al
stream
public
sta$c
long
sequen$alSum(long
n)
{
return
Stream.iterate(1L,
i
-‐>
i
+
1)
.limit(n)
.reduce(Long::sum).get();
}
80
98ms
81. Step
3:
parallel
stream
public
sta$c
long
sequen$alSum(long
n)
{
return
Stream.iterate(1L,
i
-‐>
i
+
1).parallel()
.limit(n)
.reduce(Long::sum).get();
}
81
193ms!!
82. Step
4:
improved
sequen$al
stream
public
sta$c
long
rangedSum(long
n)
{
return
LongStream.rangeClosed(1,
n)
.reduce(Long::sum).getAsLong();
}
82
17ms
83. Step
5:
improved
parallel
stream
public
sta$c
long
rangedSum(long
n)
{
return
LongStream.rangeClosed(1,
n).parallel()
.reduce(Long::sum).getAsLong();
}
83
1ms
84. Streams:
much
more
(1)
84
• Infinite
streams
• Collectors:
– collect
– groupingBy
– par$$onBy
85. Op$onal<T>
85
• A
new
class
added
in
Java8:
java.u$l.Op$onal
• Indicates
the
presence
or
absence
of
a
value
• has
a
bunch
of
method
to
simplify
and
force
“null”
checking
Op$onal<Transac$on>
optTransac$on
=
numbers.stream().findAny(t
-‐>
t.getValue()
<
200);
87. Op$onal:
do
something
if
there’s
a
value
87
Instead
of:
if(transac$on
!=
null){
System.out.println(t);
}
Write:
optTransac$on.ifPresent(System.out::println);
93. Default
methods
93
• Interfaces
in
Java
8
can
contain
implementa$on
code
From
List.java:
default
void
sort(Comparator<?
super
E>
c){
Collec$ons.sort(this,
c);
}
94. Goal
94
• Evolve
libraries
• Adding
a
method
to
an
interface
is
source
incompa$ble
– all
implementers
need
to
support
the
method
– recompiling
a
class
implemen$ng
the
interface
will
fail
• Providing
a
“default”
implementa$on
solves
the
problem
97. Applica$ons:
mul$ple
inheritance
97
• A
class
has
been
allowed
to
implement
mul$ple
interfaces
since
day
1
of
Java!
public
class
ArrayList<E>
extends
AbstractList<E>
implements
List<E>,
RandomAccess,
Cloneable,
java.io.Serializable,
Iterable<E>,
Serializable
{
…
}
103. Resolu$on
rules
103
1.
Classes
always
win.
A
method
declara$on
in
the
class
or
a
superclass
takes
priority
over
any
default
method
declara$on.
2.
Otherwise,
the
method
with
the
same
signature
in
the
most
specific
default-‐providing
interface
is
selected.
(If
B
extends
A,
B
is
more
specific
than
A).
105. Use
case
1
105
public
interface
A{
public
default
void
hello()
{
System.out.println("Hello
from
A");
}
}
public
interface
B
extends
A{
public
default
void
hello()
{
System.out.println("Hello
from
B");
}
}
public
class
C
implements
B,
A
{
public
sta$c
void
main(String...
args)
{
new
C().hello();
//
??
}
}
106. Use
case
2
(a)
106
public
class
D
implements
A{
}
public
class
C
extends
D
implements
B,
A
{
public
sta$c
void
main(String...
args)
{
new
C().hello();
//
??
}
}
107. Use
case
2
(b)
107
public
class
D
implements
A{
public
void
hello(){
System.out.println(“Hello
from
D”);
}
}
public
class
C
extends
D
implements
B,
A
{
public
sta$c
void
main(String...
args)
{
new
C().hello();
//
??
}
}