The document discusses Java 8 lambda expressions and how they improved Java by allowing for anonymous functions. It provides examples of code before and after Java 8 that demonstrate lambda expressions providing a clearer syntax compared to anonymous inner classes. Specifically, it shows how lambda expressions allowed sorting a list of strings in a more readable way. It also discusses how functions can be treated as data by being passed as parameters or returned from other functions.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
OOP and FP - Become a Better ProgrammerMario Fusco
ย
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
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.
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
ย
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developerโs toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
A minimal collection of most wanted and widely accepted idioms and coding conventions for C++ development presented with examples and explanations. The lecture targets performance oriented codes so emphasis is on performance-friendly techiques.
Topics covered:
1) Design issues: idioms and best practices
- Resource Aquisition Is Initialization (RAII)
- Ownership semantics and smart pointers
- Header files: dependencies and decoupling
2) Objects Construction/Destruction/Copying
- Designing constructors
- Rule Of Three
- Transactional programming
3) Namespaces
- ADL/Koenig Lookup
4) Static analyzers
Lambda expressions are a new and important feature that has been included in Java SE 8. It provides a way to represent one method interface using an expression. A lambda expression is like a method, it provides a list of formal parameters and a body (which can be an expression or a block of code) expressed in terms of those parameters.
OOP and FP - Become a Better ProgrammerMario Fusco
ย
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
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.
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
ย
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developerโs toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
A minimal collection of most wanted and widely accepted idioms and coding conventions for C++ development presented with examples and explanations. The lecture targets performance oriented codes so emphasis is on performance-friendly techiques.
Topics covered:
1) Design issues: idioms and best practices
- Resource Aquisition Is Initialization (RAII)
- Ownership semantics and smart pointers
- Header files: dependencies and decoupling
2) Objects Construction/Destruction/Copying
- Designing constructors
- Rule Of Three
- Transactional programming
3) Namespaces
- ADL/Koenig Lookup
4) Static analyzers
Lambda expressions are a new and important feature that has been included in Java SE 8. It provides a way to represent one method interface using an expression. A lambda expression is like a method, it provides a list of formal parameters and a body (which can be an expression or a block of code) expressed in terms of those parameters.
A short introduction to, and practical experiment of, the new features available to the Java craftsman.
Java 8 is mostly about new functional programming paradigms.
Lambdas, method references and the stream API are powerful and yet sometimes hard to understand concepts. These slides are mainly about describing those features, in a way, that is easy to understand, through, analogies and thought experiements discussions.
Why is Java relevant? New features of Java8 xshyamx
ย
Presentation slides from ISDC2013 held on 16-mar-2013
http://www.siliconindia.com/events-overview/India--Software-Developer-Conference-Bangalore-ISDC_2013Blr.html
Introduction to functional programming with java 8JavaBrahman
ย
Recently gave a presentation in a Java Meetup in Bangalore on basics of functional programming, new functional features in Java 8, and introduction to the basic concepts of functional interfaces and lambda expressions...
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
Code is available at https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
Code is available at https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
This is a 3 part series on Java8 Features. Drop me an email for a discussion - singh.marut@gmail.com
https://github.com/singhmarut/java8training
Videos available at my youtube channel https://www.youtube.com/channel/UCBM4yHwfjQ_syW6Lz8kYpmA
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.
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
ย
While the new Streams API has been a great showcase for lambda methods, there are many other ways this new language feature can be used to make friendlier APIs and more expressive code. Lambdas can be used for a number of tasks which historically required significant boilerplate, type-unsafe constructs, or both. From new ways to express metedata, to emulating Groovy's null-safe navigation operator, we'll take a look at a myriad of ways, big and small, that you can use lambdas to improve APIs and streamline your code. We'll also look at some of the limitations of lambdas, and some techniques for overcoming them.
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...Databricks
ย
We can think of an Apache Spark application as the unit of work in complex data workflows. Building a configurable and reusable Apache Spark application comes with its own challenges, especially for developers that are just starting in the domain. Configuration, parametrization, and reusability of the application code can be challenging. Solving these will allow the developer to focus on value-adding work instead of mundane tasks such as writing a lot of configuration code, initializing the SparkSession or even kicking-off a new project.
This presentation will describe using code samples a developerโs journey from the first steps into Apache Spark all the way to a simple open-source framework that can help kick-off an Apache Spark project very easy, with a minimal amount of code. The main ideas covered in this presentation are derived from the separation of concerns principle.
The first idea is to make it even easier to code and test new Apache Spark applications by separating the application logic from the configuration logic.
The second idea is to make it easy to configure the applications, providing SparkSessions out-of-the-box, easy to set-up data readers, data writers and application parameters through configuration alone.
The third idea is that taking a new project off the ground should be very easy and straightforward. These three ideas are a good start in building reusable and production-worthy Apache Spark applications.
The resulting framework, spark-utils, is already available and ready to use as an open-source project, but even more important are the ideas and principles behind it.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
ย
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they donโt know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. Weโll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
Reactive Programming in the Browser feat. Scala.js and PureScriptLuka Jacobowitz
ย
Creating User Interfaces has traditionally been a mostly imperative matter and building UIs in a functional way has never really been easy. In this talk weโll learn how to build UIs using only pure functions with the help of Reactive Programming and Scala.js or PureScript. We will take a look at the strengths and weaknesses of each languages, explore OutWatch, a new UI Library based on Rx, look at what works well, identify more challenging tasks and unlock the full potential of functional design and type safety with functional programming in the browser.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
ย
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navyโs DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATOโs (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
DevOps and Testing slides at DASA ConnectKari Kakkonen
ย
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
ย
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Le nuove frontiere dell'AI nell'RPA con UiPath AutopilotโขUiPathCommunity
ย
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalitร di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
๐ Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
๐จโ๐ซ๐จโ๐ป Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
ย
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
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.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
ย
Clients donโt know what they donโt know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clientsโ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
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.
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
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
ย
Building better applications for business users with SAP Fiori.
โข What is SAP Fiori and why it matters to you
โข How a better user experience drives measurable business benefits
โข How to get started with SAP Fiori today
โข How SAP Fiori elements accelerates application development
โข How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
โข How SAP Fiori paves the way for using AI in SAP apps
14. 2006 - Gosling: "We will never have closures in Java"
2008 - Reinhold: "We will never have closures in Java"
Project Lambda
15. 2007 - 3 different proposals for closures in Java
2009 - Start of project Lambda (JSR 335)
Project Lambda
16. JDK 8: General Availability - 2014/04/18
โ
โ
โ
โ
2006
2007
2008
2009
-
Gosling: "We will never have closures in Java"
3 different proposals for closures in Java
Reinhold: "We will never have closures in Java"
Start of project Lambda (JSR 335)
22. Languages that support anonymous functions
ActionScript
Ada
C
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go
Gosu
Groovy
Haskell
Java
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal
Objective-C
Pascal
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
23. Languages that no support anonymous functions
ActionScript
Ada
C
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go
Gosu
Groovy
Haskell
Java
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal
Objective-C
Pascal
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
24. Languages that no support anonymous functions
ActionScript
Ada (1977)
C (1969)
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go
Gosu
Groovy
Haskell
Java
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal
Objective-C
Pascal (1969)
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
25. Languages that no support anonymous functions
ActionScript
Ada
C
C#
C++
Clojure
Curl
D
Dart
Dylan
Erlang
Elixir
F#
Frink
Go
Gosu
Groovy
Haskell
Java (1995)
JavaScript
Lisp
Logtalk
Lua
Mathematica
Maple
Matlab
Maxima
OCaml
Octave
Object Pascal
Objective-C
Pascal
Perl
PHP
Python
R
Racket
Ruby
Scala
Scheme
Smalltalk
Standard ML
TypeScript
Tcl
Vala
Visual Basic .NET
Visual Prolog
38. @FunctionalInterface
interface Adder {
int add(int a, int b);
}
????? func = (int a, int b) -> { return a + b };
Adder shortFunc = (a, b) -> a + b;
Functional Interface
39. @FunctionalInterface
interface Adder {
int add(int a, int b);
}
Adder func = (int a, int b) -> { return a + b };
Adder shortFunc = (a, b) -> a + b;
Functional Interface
44. // Spring
jdbcTemplate.queryForObject("select * from student where id = ?",
new Object[]{1212l},
new RowMapper() {
public Object mapRow(ResultSet rs, int n) throws SQLException {
return new Student(rs.getString("name"), rs.getInt("age"));
}
});
// Google Guava
Iterables.filter(persons, new Predicate<Person>() {
public boolean apply(Person p) {
return p.getAge() > 18;
}
});
Lambda in Java
45. // Spring
jdbcTemplate.queryForObject("select * from student where id = ?",
new Object[]{1212l},
new RowMapper() {
public Object mapRow(ResultSet rs, int n) throws SQLException {
return new Student(rs.getString("name"), rs.getInt("age"));
}
});
// Google Guava
Iterables.filter(persons, new Predicate<Person>() {
public boolean apply(Person p) {
return p.getAge() > 18;
}
});
Lambda in Java
46. // Before Java 8
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
// Java 8
Collections.sort(strings, (s1, s2) -> s1.compareTo(s2));
Bulky syntax!
53. public void withFile(String fileName) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Print each line to STDOUT
54. public void withFile(String fileName) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
DB.store(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Store each line to DB
55. public void withFile(String fileName) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// insert code at here
}
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(line);
} finally {
if (bufferedReader != null)
DB.store(line);
bufferedReader.close();
}
}
Duplicate and Variation
56. public void withFile(String fileName, Consumer<String> work) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
work.accept(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Refactoring with Lambda
57. public void withFile(String fileName, Consumer<String> work) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
work.accept(line);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Refactoring with Lambda
58. // print each line to stdout
withFile(filename, line -> System.out.println(line));
// store each line to db
withFile(filename, line -> storeToDb(line));
// print and store each line
withFile(filename, line -> {
System.out.println(line)
storeToDb(line);
});
Refactoring with Lambda
59. // print each line to stdout
withFile(filename, line -> System.out.println(line));
// store each line to db
withFile(filename, line -> storeToDb(line));
Refactoring with Lambda
62. // Java8 - print each line to stdout
withFile(filename, line -> System.out.println(line));
// Java8 - store each line to db
withFile(filename, line -> storeToDb(line));
// Scala - print each line to stdout
withFile(filename) {
line => println(line)
}
// Scala - store each line to db
withFile(filename) {
line => storeToDb(line)
}
Multiple parameter lists(curried function)
64. // External Iterator
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}
// Internal Iterator
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
Internal iterator? External iterator?
65. // External Iterator
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}
// Internal Iterator
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
When you pass a function object to a method to run over a
collection, that is an internal iterator
68. // Java8:: print each line to stdout
withFile(filename, line -> System.out.println(line));
// Java8 - store each line to db
withFile(filename, line -> storeToDb(line));
// Scala - print each line to stdout
withFile(filename) {
line => println(line)
}
// Scala:: store each line to db
withFile(filename) {
line => storeToDb(line)
}
Internal iterator
69. // Java8:: print each line to stdout
withFile(filename, line -> System.out.println(line));
// Java8 - store each line to db
withFile(filename, line -> storeToDb(line));
// Scala - print each line to stdout
withFile(filename) {
line => println(line)
}
// Scala:: store each line to db
withFile(filename) {
line => storeToDb(line)
}
Iterator
70. No more loop with Scala
โ
โ
Project Lambda J
Google guava-libraries/
71. case class Person(firstName: String, lastName: String, age:Int, male: Boolean)
case class Sale(buyer: Person, seller: Person, car: Car, cost: Double)
case class Car(brand: String, model: String, year: Int, originalValue: Double)
LambdaJ Demo Data Model
72. object db {
// car
val sonata = Car("Hyundai", "Sonata", 1982, 30000000)
val santafe = Car("Hyundai", "Santafe", 1990, 50000000)
val k7 = Car("KIA", "K7", 2000, 50000000)
val k9 = Car("KIA", "K9", 2008, 70000000)
val orlando = Car("GM", "Orlando", 2011, 30000000)
val chevrolet = Car("GM", "Chevrolet", 2010, 50000000)
val alpheon = Car("GM", "Alpheon", 2012, 70000000)
def cars = List(sonata, santafe, k7, k9, orlando, chevrolet, alpheon);
// person
val daewon = Person("daewon", "jeong", 31, true)
val youngtek = Person("youngtek", "hong", 32, true)
val jiwong = Person("jiwong", "kang", 34, true)
val taehee = Person("taehee", "kim", 32, false)
def persons = List(youngtek, daewon, jiwong, taehee)
// sales: map person/car
def sales = List(Sale(daewon, taehee, sonata, 30000000),
Sale(daewon, youngtek, santafe, 50000000),
Sale(daewon, jiwong, santafe, 50000000),
Sale(jiwong, taehee, santafe, 50000000),
Sale(taehee, daewon, chevrolet, 50000000),
Sale(youngtek, daewon, chevrolet, 50000000),
Sale(youngtek, taehee, orlando, 30000000),
Sale(taehee, jiwong, chevrolet, 30000000))
}
73. // Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Hyundai")) {
salesOfAHyundai.add(sale);
}
}
// Functional version
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")
ํ๋์ฐจ๋ฅผ ํ๋งคํ๋ ๋ชจ๋ Sales๊ฐ์ฒด๋ฅผ ์ ํ
74. // Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Hyundai")) {
salesOfAHyundai.add(sale);
}
}
// Functional version
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")
sales ๋ชฉ๋ก์์ car brand๊ฐ Hyundai์ธ ๊ฒ๋ง ํํฐ๋ง
75. // Iterative version
List<Sale> salesOfAHyundai = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Hyundai")) {
salesOfAHyundai.add(sale);
}
}
// Functional version
val salesOfHyundai = db.sales.filter(_.car.brand == "Hyundai")
Select all sales of Hyundai
76. // Iterative version
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) {
costs.add(car.getOriginalValue());
}
// Functional version
val costs = db.cars.map(_.originalValue)
์๋์ฐจ์ Original ๊ฐ๊ฒฉ ๋ชฉ๋ก์ ์์ฑ
77. // Iterative version
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) {
costs.add(car.getOriginalValue());
}
// Functional version
val costs = db.cars.map(_.originalValue)
cars ๋ชฉ๋ก์ผ๋ก๋ถํฐ originalValue๋ฅผ ์ถ์ถํด์ ์ ๋ชฉ๋ก์ ์์ฑ
78. // Iterative version
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) {
costs.add(car.getOriginalValue());
}
// Functional version
val costs = db.cars.map(_.originalValue)
Extract carโs original cost
79. // Iterative version
double maxCost = 0.0;
for (Sale sale : sales) {
double cost = sale.getCost();
if (cost > maxCost) {
maxCost = cost;
}
}
// Functional version
val maxCost = db.sales.maxBy(_.cost).cost
๊ฐ์ฅ ๋น์ธ๊ฒ ํ๋งคํ ๊ฐ์?
80. // Iterative version
double maxCost = 0.0;
for (Sale sale : sales) {
double cost = sale.getCost();
if (cost > maxCost) {
maxCost = cost;
}
}
// Functional version
val maxCost = db.sales.maxBy(_.cost).cost
Find most costly sale
81. // Iterative version
// 01. find youngest person in persons
Person youngest = null;
for (Person person : persons){
if (youngest == null || person.getAge() < youngest.getAge()) {
youngest = person;
}
}
// 02. find buyer have age equal to younggest person
List<Sale> buys = new ArrayList<Sale>();
for (Sale sale : sales){
if (sale.getBuyer().equals(youngest)) {
buys.add(sale);
}
}
// Functional version
val youngestPerson = db.persons.minBy( _.age )
val buys = db.sales.filter( _.buyer == youngestPerson )
๊ฐ์ฅ ์ด๋ฆฐ ์ฌ๋๊ณผ ๋์ด๊ฐ ๊ฐ์ ํ๋งค์๋ค ์ฐพ๊ธฐ
82. // Iterative version
// 01. find youngest person in persons
Person youngest = null;
for (Person person : persons){
if (youngest == null || person.getAge() < youngest.getAge()) {
youngest = person;
}
}
// 02. find buyer have age equal to younggest person
List<Sale> buys = new ArrayList<Sale>();
for (Sale sale : sales){
if (sale.getBuyer().equals(youngest)) {
buys.add(sale);
}
}
// Functional version
val youngestPerson = db.persons.minBy( _.age )
val buys = db.sales.filter( _.buyer == youngestPerson )
Find buys of youngest person
83. // 01. ๊ฐ์ฅ ์ด๋ฆฐ ์ฌ๋์ ์ฐพ๊ณ
val youngestPerson = db.persons.minBy( _.age )
// 02. ๊ฐ์ฅ ์ด๋ฆฐ ์ฌ๋๊ณผ ๋์ด๊ฐ ๊ฐ์ ํ๋งค์๋ค์ ์ฐพ๋๋ค.
val buys = db.sales.filter( _.buyer == youngestPerson )
Find buys of youngest person
84. // Iterative version
Map<String, List<Car>> carsByBrand = new HashMap<>();
for (Car car : db.getCars()) {
List<Car> carList = carsByBrand.get(car);
if (carList == null){
carList = new ArrayList<Car>();
carsByBrand.put(car.getBrand(), carList);
}
carList.add(car);
}
// Functional version
val carsByBrand = db.cars.groupBy(_.brand)
brand ๊ธฐ์ค์ผ๋ก car๋ฅผ ๊ทธ๋ฃจํ
85. // Iterative version
Map<String, List<Car>> carsByBrand = new HashMap<>();
for (Car car : db.getCars()) {
List<Car> carList = carsByBrand.get(car);
if (carList == null){
carList = new ArrayList<Car>();
carsByBrand.put(car.getBrand(), carList);
}
carList.add(car);
}
// Functional version
val carsByBrand = db.cars.groupBy(_.brand)
Select * from cars group by brand
86. // Iterative version
Map<String, List<Car>> carsByBrand = new HashMap<>();
for (Car car : db.getCars()) {
List<Car> carList = carsByBrand.get(car);
if (carList == null){
carList = new ArrayList<Car>();
carsByBrand.put(car.getBrand(), carList);
}
carList.add(car);
}
// Functional version
val carsByBrand = db.cars.groupBy(_.brand)
Index cars by brand
87. // Iterative version
Map<Car, Integer> carsBought = new HashMap<Car, Integer>();
for (Sale sale : sales) {
Car car = sale.getCar();
int boughtTimes = carsBought.get(car);
carsBought.put(car, boughtTimes == null ? 1 : boughtTimes+1);
}
Car mostBoughtCarIterative = null;
int boughtTimesIterative = 0;
for (Entry<Car, Integer> entry : carsBought.entrySet()) {
if (entry.getValue() > boughtTimesIterative) {
mostBoughtCarIterative = entry.getKey();
boughtTimesIterative = entry.getValue();
}
}
๊ฐ์ฅ ๋ง์ด ๊ตฌ๋งคํ ์ฐจ
88. // Functional version
val carsBought = db.sales.groupBy( _.car ).mapValues( _.length )
val mostBoughtCar = carsBought.maxBy {
case (_, boughtCount) => boughtCount
}._1
val boughtTimes = carsBought(mostBoughtCar)
Find most bought car
89. // Functional version
val carsBought = db.sales.groupBy( _.car ).mapValues( _.length )
val mostBoughtCar = carsBought.maxBy {
case (_, boughtCount) => boughtCount
}._1
val boughtTimes = carsBought(mostBoughtCar)
Find most bought car
90. // Iterative version
Map<Person,Map<Person,Sale>> map = new HashMap<Person, Map<Person,Sale>>();
for (Sale sale : sales) {
Person buyer = sale.getBuyer();
Map<Person, Sale> buyerMap = map.get(buyer);
if (buyerMap == null) {
buyerMap = new HashMap<Person, Sale>();
map.put(buyer, buyerMap);
}
buyerMap.put(sale.getSeller(), sale);
}
Person youngest = null;
Person oldest = null;
for (Person person : persons) {
if (youngest == null || person.getAge() < youngest.getAge()){
youngest = person;
}
if (oldest == null || person.getAge() > oldest.getAge()) {
oldest = person;
}
}
Group sales by
Sale saleFromYoungestToOldest = map.get(youngest).get(oldest);
buyer and sellers
91. // Functional version
val map = db.sales.groupBy(_.buyer).mapValues{
ls => ls.groupBy(_.seller).mapValues(_.head)
}
val youngest = db.persons.minBy(_.age)
val oldest = db.persons.maxBy(_.age)
val saleFromYoungestToOldest = map(youngest)(oldest)
Group sales by buyer and sellers
92. Java8 Streams vs Scala For Comprehension
โ
โ
streams and sql
โ how-java-emulates-sql
for comprehension
93.
94. // sql
select sum(salary)
from people
where gender = 'FEMALE'
// Java8 stream with lambda
people.stream()
.filter(p -> p.getGender() == Person.Gender.FEMALE)
.mapToInt(p -> p.getSalary())
.sum();
๋ชจ๋ ์ฌ์ฑ์ ๊ธ์ฌ์ ํฉ
95. // sql
select sum(salary)
from people
where gender = 'FEMALE'
// scala for comprehension
(for (p <- people;
(if p.gender == Person.Gender.FEMALE))
yield p.salary).sum()
Find the sum of all the salaries of all the females.
96. // sql
select sum(salary)
from people
where gender = 'FEMALE'
// scala for comprehension
(for (p <- people;
(if p.gender == Person.Gender.FEMALE))
yield p.salary).sum()
Find the sum of all the salaries of all the females.
97. // sql
select distinct(firstName)
from people
where gender = 'MALE'
// Java8 stream with lambda
people.stream()
.filter(p -> p.getGender() == Person.Gender.MALE)
.map(p -> p.getFirstName())
.distinct()
์ค๋ณต์ ์ ๊ฑฐํ ๋ชจ๋ ๋จ์ฑ์ ์ด๋ฆ
98. // sql
select distinct(firstName)
from people
where gender = 'MALE'
// scala for comprehension
(for (p <- people;
if (p.getGender == Person.Gender.MALE))
yield p.firstName).distinct
Prepare a list of all (distinct) first names of the males
99. // sql
select distinct(firstName)
from people
where gender = 'MALE'
// scala for comprehension
(for (p <- people;
if (p.getGender == Person.Gender.MALE))
yield p.firstName).distinct
Prepare a list of all (distinct) first names of the males
100. // sql
๋์ด๊ฐ ๊ฐ์ฅ ๋ง์ ๋จ์๋ค
select *
from
people
where age =
(select max(age) from people where gender ='MALE' )
and
gender ='MALE'
// Java8
int maxAge = people.stream().max(
(p1, p2) -> p1.getAge() - p2.getAge()).get());
people.stream()
.filter(p -> p.getGender() == Person.Gender.MALE
&& p.getAge() == max_age)
.collect(Collections.toList()));
// scala for comprehension
for {
maxAge <- Seq(person.maxBy(_.age));
p <- people;
if (p.age == maxAge && p.gender == Person.Gender.MALE)
} yield p
101.
102. Is Java8 a functional language?
โ
What is Functional Programming?
โ Immutable state
โ Functions as first class citizens
โ Persistent data structure
105. Java8
โ
โ
โ
Immutable state
Functions as first class citizens
Persistent data structure
Scala
โ
โ
โ
Immutable state
Functions as first class citizens
Persistent data structure
106. Java8 is not a functional language.
โ
โ
โ
So what?
Real-world programming isn't always perfectly functional
Java is steel the most popular language in the world
Functional programming is not a silver bullet
110. Lambda? Closure?
// lambda is just an anonymous function
Collection.filter(lists, e โ> e.length() >= 5)
// closure is function that closes over the environment it was defined
int min = 5;
Collection.filter(lists, e -> e.length() >= min);
111. Lambda? Closure?
// lambda is just an anonymous function
Collection.filter(lists, e โ> e.length() >= 5)
// closure is function that closes over the environment it was defined
int min = 5;
Collection.filter(lists, e -> e.length() >= min);