When embracing Java 8 we walk down the yellow brick road to the wizard of lambdas. That road usually starts from the fear and terror of learning their syntax until finally getting to understand them and opening our minds to the fruitful fields of functional programming. But this road eventually reaches a final stage: the lambda abuse.
To master the lambdas art means to know when to use them and when not to not damage your brain and, most importantly, other Java developers’. Keep your code readable and maintainable, avoid becoming a lambda addict!
Java 8 Stream API. A different way to process collections.David Gómez García
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.
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
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.
Java 8 Stream API. A different way to process collections.David Gómez García
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.
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
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.
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
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.
This is a beginner's guide to Java 8 Lambdas, accompnied with executable code examples which you can find at https://github.com/manvendrasinghkadam/java8streams. Java 8 Streams are based on Lambdas, so this presentation assumes you know Lambdas quite well. If don't then please let me know I'll create another presentation regarding it with code examples. Lambdas are relatively easy to use and with the power of stream api you can do functional programming in Java right from start. This is very cool to be a Java programmer now.
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.
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"
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
The slides from the talk I gave at Oracle III #JuevesTecnológicos in Madrid.
A review of how the ParallelStreams Work in Java 8 and some considerations we must know in order to get the better performance from the concurrent data processing in #Java8
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Lambda and Stream Master class - part 1José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This first part covers Lambda Expressions and API design with functional interfaces.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
This tutorial walks through tons of examples. You will learn everything you need to know about lambdas and functional programming in Java 8. I'm the supplier. You’re the consumer (and you will get the joke after the session).
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
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.
This is a beginner's guide to Java 8 Lambdas, accompnied with executable code examples which you can find at https://github.com/manvendrasinghkadam/java8streams. Java 8 Streams are based on Lambdas, so this presentation assumes you know Lambdas quite well. If don't then please let me know I'll create another presentation regarding it with code examples. Lambdas are relatively easy to use and with the power of stream api you can do functional programming in Java right from start. This is very cool to be a Java programmer now.
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.
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"
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
The slides from the talk I gave at Oracle III #JuevesTecnológicos in Madrid.
A review of how the ParallelStreams Work in Java 8 and some considerations we must know in order to get the better performance from the concurrent data processing in #Java8
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Lambda and Stream Master class - part 1José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This first part covers Lambda Expressions and API design with functional interfaces.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
This tutorial walks through tons of examples. You will learn everything you need to know about lambdas and functional programming in Java 8. I'm the supplier. You’re the consumer (and you will get the joke after the session).
Do you want to learn functional programming in Java using lambda expressions introduced in Java 8? Do you want to explore the foundational concepts to explore powerful stream API? This presentation provides an overview of lambda functions introduced in Java 8 through examples. Topics covered: What is functional programming, creating lambda expressions, functional interfaces, built-in functional interfaces, and method references.
Make sure you have JDK 8 installed for trying out the programs as you go through the self-contained programming examples.
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
Workshop slides from the Alt.Net Seattle 2011 workshop. Presented by Wes Dyer and Ryan Riley. Get the slides and the workshop code at http://rxworkshop.codeplex.com/
Hierarchical free monads and software design in fpAlexander Granin
I invented the approach I call "Hierarchical Free Monads". It helps to build applications in Haskell with achieving all the needed code quality requirements. I tested this approach in several real world projects and companies, and it works very well.
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.
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Similar to The... Wonderful? World of Lambdas (20)
Aterrizando en JS: Consejos para [node]sesperar en el intentoEsther Lozano
Para quien aún mire a JS con recelo o quiera repasar algunos de sus aspectos clave, os traigo una serie de consejos que, espero, os hagan ver JS con mejores ojos.
Aterrizando en JS: consejos para [node]sesperar en el intentoEsther Lozano
Cuando pasé de desarrollar en Java a adentrarme en el para mí desconocido mundo JS mi día era una sucesión de: "pero... wtf is this?" (pun intended). Con el tiempo, lecturas varias y la paciente ayuda de mis compis fui viendo la luz de la mano de Node, Typescript (¡no sin mis tipos!) y demás amigas del festival JS. Porque no, JS no es malvado... sólo rarito de conocer :P
Así que para quien aún mire a JS con recelo o quiera repasar algunos de sus aspectos clave, os traigo una serie de consejos que, espero, os hagan ver JS con mejores ojos.
Una Javera en JS: consejos para [node]sesperar en el intentoEsther Lozano
Cuando hace unos meses pasé de desarrollar en Java a adentrarme en el oscuro mundo JS mi día era una sucesión de: "pero... what is this?" (pun intended). Con el tiempo, lecturas varias y las pacientes explicaciones de mis compis fui viendo la luz de la mano de Node, Typescript (¡no sin mis tipos!) y demás amigas del festival JS. Porque no, JS no es malvado... sólo rarito de conocer :P Así que para las que aún le miráis con recelo os traigo una serie de consejos que, espero, os hagan los primeros contactos un poquito más fácil.
Geb+spock: let your functional tests live long and prosperEsther Lozano
Functional testing, as any other testing, is important to ensure the health of our apps. However, functional tests are often tricky, too susceptible to change, and their maintenance ends up being a nightmare. Are we hopeless then? Not at all! Luckily, there are tools to ease this task like Geb and Spock, which help us to create well structured, comprehensive, and easy to maintain tests. In this talk we will review these tools, showing different options for creating the tests.
Geb+spock: larga y próspera vida a tus tests funcionalesEsther Lozano
El testing funcional, como cualquier otro testing, es importante para asegurar el buen funcionamiento de una aplicación. Sin embargo los tests funcionales suelen ser farragosos, muy susceptibles a cambios y mantenerlos puede convertirse en una pesadilla. Por suerte existen herramientas como Geb y Spock que nos permiten hacer tests bien estructurados, intuitivos y fáciles de mantener. Esta charla pretende ser una introducción a estas herramientas, mostrando distintas formas de hacer los tests y poniéndolo todo en funcionamiento.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Why React Native as a Strategic Advantage for Startup Innovation.pdfayushiqss
Do you know that React Native is being increasingly adopted by startups as well as big companies in the mobile app development industry? Big names like Facebook, Instagram, and Pinterest have already integrated this robust open-source framework.
In fact, according to a report by Statista, the number of React Native developers has been steadily increasing over the years, reaching an estimated 1.9 million by the end of 2024. This means that the demand for this framework in the job market has been growing making it a valuable skill.
But what makes React Native so popular for mobile application development? It offers excellent cross-platform capabilities among other benefits. This way, with React Native, developers can write code once and run it on both iOS and Android devices thus saving time and resources leading to shorter development cycles hence faster time-to-market for your app.
Let’s take the example of a startup, which wanted to release their app on both iOS and Android at once. Through the use of React Native they managed to create an app and bring it into the market within a very short period. This helped them gain an advantage over their competitors because they had access to a large user base who were able to generate revenue quickly for them.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
4. A real chat
Just saw a simple and
useful case for lambdas:
better logging!
5. A real chat
Just saw a simple and
useful case for lambdas:
better logging!
A new Object
instance for each log
statement… isn’t it a
bit overkill?
6. Not sugar syntax
public class SimpleInnerClassUse {
public void executeAction(Action action) {
action.execute();
}
public static void main (String ... args) {
new SimpleInnerClassUse().executeAction(new Action() {
@Override
public void execute() {
System.out.println("Action Executed (Inner class)");
}
});
}
}
7. Not sugar syntax
public static void main (String ... args) {
new SimpleInnerClassUse().executeAction(new Action() {
@Override
public void execute() {
System.out.println("Action Executed (Inner class)");
}public static void main(java.lang.String...);
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=3, locals=1, args_size=1
0: new #3 // class com/autentia/training/java8/lambdas/SimpleInnerClassUse
3: dup
4: invokespecial #4 // Method "<init>":()V
7: new #5 // class com/autentia/training/java8/lambdas/SimpleInnerClassUse$1
10: dup
11: invokespecial #6 // Method
com/autentia/training/java8/lambdas/SimpleInnerClassUse$1."<init>":()V
14: invokevirtual #7 // Method
executeAction:(Lcom/autentia/training/java8/functionalinterfaces/Action;)V
17: return
8. Not sugar syntax
public class SimpleLambdaUse {
public void executeAction(Action action) {
action.execute();
}
public static void main (String ... args) {
new SimpleLambdaUse().executeAction(
()-> System.out.println("action executed!"));
}
}
9. Not sugar syntax
public static void main (String ... args) {
new SimpleLambdaUse().executeAction(
()-> System.out.println("action executed!"));
}
public static void main(java.lang.String...);
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=1, args_size=1
0: new #3 // class
com/autentia/training/java8/lambdas/SimpleLambdaUse
3: dup
4: invokespecial #4 // Method "<init>":()V
7: invokedynamic #5, 0 // InvokeDynamic
#0:execute:()Lcom/autentia/training/java8/functionalinterfaces/Action;
12: invokevirtual #6 // Method
executeAction:(Lcom/autentia/training/java8/functionalinterfaces/Action;)V
15: return
10. Not sugar syntax
Less impact in ClassLoader, Memory & GC
$ ls -la com/autentia/training/java8/lambdas/*.class
com/autentia/training/java8/lambdas/SimpleInnerClassUse$1.class
com/autentia/training/java8/lambdas/SimpleInnerClassUse.class
com/autentia/training/java8/lambdas/SimpleLambdaUse.class
11. Not so new: SAM Types & @FunctionalInterface
Have you ever used…?
public interface Runnable {
public abstract void run();
}
12. Not so new: SAM Types & @FunctionalInterface
Have you ever used…?
public interface Runnable {
public abstract void run();
}
Single Abstract Method (SAM type)
13. Not so new: SAM Types & @FunctionalInterface
Have you ever used…?
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
Single Abstract Method (SAM type)
Functional Interface
14. From imperative to declarative
Imperative code:
List<Integer> numbers = //List of random numbers
List<Integer> evenNumbers = new ArrayList<>();
for (int i : numbers) {
if (i % 2 == 0) {
evenNumbers.add(i);
}
}
15. From imperative to declarative
Declarative code:
List<Integer> numbers = //List of random numbers
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(toList());
16. From imperative to declarative
More concise:
phoneCallLog.stream()
.filter(phoneCall ->
phoneCall.getTime().getMonth() == Month.JUNE)
.map(phoneCall -> phoneCall.getContact().getName())
.distinct()
.forEach(System.out::println);
17. Lambdas & its context
public class SimpleInnerClassUse {
public static void main (String ... args) {
new SimpleInnerClassUse().executeAction(new Action() {
public String whoAmI() {
return this.getClass().getName();
}
@Override
public void execute() {
System.out.println("I am " + this.whoAmI());
}
});
}
}
18. Lambdas & its context
public class SimpleInnerClassUse {
public static void main (String ... args) {
new SimpleInnerClassUse().executeAction(new Action() {
public String whoAmI() {
return this.getClass().getName();
}
@Override
public void execute() {
System.out.println("I am " + this.whoAmI());
}
});
}
}
19. Lambdas & its context
public class SimpleInnerClassUse {
public static void main (String ... args) {
new SimpleInnerClassUse().executeAction(new Action() {
public String whoAmI() {
return this.getClass().getName();
}
@Override
public void execute() {
System.out.println("I am " + this.whoAmI());
}
});
}
}
I am com.autentia.training.java8.lambdas.SimpleInnerClassUse$1
20. Lambdas & its context
public class SimpleLambdaUse {
public static void main (String ... args) {
new SimpleLambdaUse().invokeFromInstance();
}
public void invokeFromInstance() {
executeAction(() -> System.out.println("I am " + this.whoAmI()));
}
public String whoAmI() {
return SimpleLambdaUse.class.getSimpleName();
}
}
21. public class SimpleLambdaUse {
public static void main (String ... args) {
new SimpleLambdaUse().invokeFromInstance();
}
public void invokeFromInstance() {
executeAction(() -> System.out.println("I am " + this.whoAmI()));
}
public String whoAmI() {
return this.getClass().getSimpleName();
}
}
Lambdas & its context
22. public class SimpleLambdaUse {
public static void main (String ... args) {
new SimpleLambdaUse().invokeFromInstance();
}
public void invokeFromInstance() {
executeAction(() -> System.out.println("I am " + this.whoAmI()));
}
public String whoAmI() {
return this.getClass().getSimpleName();
}
}
Lambdas & its context: this & super
I am SimpleLambdaUse
23. Lambdas & its context
● Variable capture? Use variable inherited from context?
○ Stateless lambdas
()->System.out.println("Doing Stuff...")
○ Capturing lambdas
() -> System.out.println(seeds[Math.round(Math.random()*10)])
25. The slopes of anonymous inner classes
● First use case: lambdas as replacement for anonymous inner classes
ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.submit(
new Runnable() {
@Override
public void run() {
System.out.println("doing stuff...");
}
}
);
() -> void
26. The slopes of anonymous inner classes
● First use case: lambdas as replacement for anonymous inner classes
ExecutorService threadPool = Executors.newCachedThreadPool();
threadPool.submit(()->System.out.println("Doing Stuff..."));
() -> void
27. The fields of java.util.function
Do you remember?
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
29. The fields of java.util.function
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Function<RowSet, Contact> contactJdbcMapper = row -> {
Contact c = new Contact();
c.setName(row.getString(0));
...
return c;
}
30. The fields of java.util.function
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Function<RowSet, Contact> contactJdbcMapper = row -> new Contact(row);
31. The fields of java.util.function
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
Function<RowSet, Contact> contactJdbcMapper = Contact::new;
32. The meadows of method parameters
● Parameterized behaviour → lazy usage → logging crazy example
public void log(Level level, String msg) {
if (!isLoggable(level)) {
return;
}
LogRecord lr = new LogRecord(level, msg);
doLog(lr);
}
Logger log = Logger.getLogger(LoggingCrazy.class.getSimpleName());
log.log(Level.FINE, heavyObject.expensiveToStringConversion());
33. The meadows of method parameters
● Parameterized behaviour → lazy usage → logging crazy example
public void log(Level level, Supplier<String> msgSupplier) {
if (!isLoggable(level)) {
return;
}
LogRecord lr = new LogRecord(level, msgSupplier.get());
doLog(lr);
}
Logger log = Logger.getLogger(LoggingCrazy.class.getSimpleName());
log.log(Level.FINE, () -> heavyObject.expensiveToStringConversion()
34. The meadows of method parameters
● Parameterized behaviour → lazy usage → logging crazy example
log.log(Level.FINE, heavyObject.expensiveToStringConversion());
log.log(Level.FINE, () -> heavyObject.expensiveToStringConversion());
time logging 100_000_000 times without supplier 10689 ms
time logging 100_000_000 times with supplier 102 ms
35. The loch of function composition
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
36. The loch of function composition
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
}
37. The loch of function composition
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
}
38. The loch of function composition
new OrderPriceCalculator()
.andThen( Taxes::generalTax )
.andThen( Carrier::shippingCost )
.andThen( Customer::profileDiscount )
.apply( order );
39. The cliffs of Function Return
You can return functions instead of values (lazy evaluation of return values)
public BiFunction<Integer, Integer, Integer> lazyMultiplier(int val1, int val2) {
return (x,y) -> val1*val2;
}
42. Abusing lambdas: Breaking effectively final rule
public class CapturingLambdas {
private int[] seeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private int[] calculatedValue = new int[1];
public void calculate() {
ExecutorService threadPool = Executors.newFixedThreadPool(2);
threadPool.execute(() -> calculatedValue[0] = seeds[Math.round(Math.random()*10));
}
}
43. Performance un-improvement
throw new RuntimeException(
"Two or more components with same type."
+ " Please use @Named to select one. Candidates: "
+ candidateNames.toString() );
44. Performance un-improvement
throw new RuntimeException(
"Two or more components with same type."
+ " Please use @Named to select one. Candidates: "
+ candidateNames.toString() );
java.lang.RuntimeException: Two or more components with the
same type. Please use @Named to select one. Candidates:
[Ljava.lang.String;@65f1fa47
45. Performance un-improvement
throw new RuntimeException(
"Two or more components with same type."
+ " Please use @Named to select one. Candidates: "
+ Arrays.asList(candidateNames)
.stream().collect(joining(",", "[", "]")));
46. Performance un-improvement
throw new RuntimeException(
"Two or more components with same type."
+ " Please use @Named to select one. Candidates: "
+ Arrays.asList(candidateNames)
.stream().collect(joining(",", "[", "]")));
java.lang.RuntimeException: Two or more components with the
same type. Please use @Named to select one. Candidates:
[Component1, Component2, Component3]
52. Lambdas gone wild
Can we get rid of that extra check?
public String deserializeMessage(Parser parser) {
Node root = new ObjectMapper().read(parser);
return Stream.of(Optional.ofNullable(root.get(0)))
.filter(Optional::isPresent)
.map(Optional::get)
.map(resultNode -> Optional.ofNullable(resultNode.get("result")))
.filter(Optional::isPresent)
.map(JsonNode::asText)
.findFirst()
.orElse(null);
}
54. Lambdas gone wild
After peer review, we decided to get back to:
@Override
public String deserializeMessage(Parser parser) {
Node root = new ObjectMapper().read(parser);
if (root.size() > 0) {
return Optional.ofNullable(root.get(0).get("result"))
.map(Node::asText)
.orElse(null);
} else {
return null;
}
}
Although we could have tried to split the lambda in several methods.
55. Playing with FP concepts
We start with a simple adder function
private BiFunction<Integer, Integer, Integer> adder = (x, y) -> x+y;
We need several other incrementers by a fixed value
private Function<Integer, Integer> incrementByOne = x -> x+1;
private Function<Integer, Integer> incrementByTwo = x -> x+2;
private Function<Integer, Integer> incrementByThree = x -> x+3;
56. Playing with FP concepts
We start with a simple adder function
private BiFunction<Integer, Integer, Integer> adder = (x, y) -> x+y;
We need several other incrementers by a fixed value
private Function<Integer, Integer> incrementByOne = x -> x+1;
private Function<Integer, Integer> incrementByTwo = x -> x+2;
private Function<Integer, Integer> incrementByThree = x -> x+3;
57. Playing with FP concepts
Maybe I can abstract this a little bit:
//Curryfying the increment Function
private Function<Integer, Function<Integer,Integer>> incrementBy = y -> x -> x+y;
So, I can rewrite the incrementers:
private Function<Integer, Integer> incrementByOne = x -> incrementBy.apply(1).apply(x);
private Function<Integer, Integer> incrementByTwo = x -> incrementBy.apply(2).apply(x);
private Function<Integer, Integer> incrementByThree = x -> incrementBy.apply(3).apply(x);
58. Playing with FP concepts
Wait, I can abstract (again) the incrementBy:
private Function<Integer, Integer> incrementByOne = x -> incrementBy.apply(1).apply(x);
private Function<Integer, Integer> incrementByTwo = x -> incrementBy.apply(2).apply(x);
private Function<Integer, Integer> incrementByThree =
x -> incrementBy.apply(3).apply(x);
…..
private BiFunction<Integer, Integer, Integer> sum =
(x,y) -> incrementBy.apply(x).apply(y);
Which is the base:
private BiFunction<Integer, Integer, Integer> sum = (x,y) -> x+y;
59. Playing with FP concepts
From
private Function<Integer, Integer> incrementByOne = x -> incrementBy.apply(1).apply(x);
Can be simplified as (there is a redundant function)
private Function<Integer, Integer> incrementByOne = x -> incrementBy.apply(1);
private Function<Integer, Integer> incrementByTwo = x -> incrementBy.apply(2);
private Function<Integer, Integer> incrementByThree = x -> incrementBy.apply(3);
60. Conclusions
● Simplicity vs performance
● Don’t over use: Conciseness means short and readable! Not only short
● Step back and ask a colleague to read and understand your code