Functional programming has started (re)gaining prominence in recent years, and with good reason too. Functional programs lend an elegant solution to the concurrency problem, result in more modular systems, are more concise and are easier to test. While modern languages like Scala and Clojure have embraced the functional style whole-heartedly, Java has lagged a bit behind in its treatment of functions as first-class citizens. With the advent of Java 8 and its support for lambdas, however, Java programmers can finally start reaping the power of functional programs as well. Even without Java 8, it is possible to adopt a functional style with the aid of excellent libraries such as Guava.
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
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...
Introduction to functional idioms in Java 8, language-extending functional libraries and short overview of reasons for adoption of such programming style.
Examples and snippets available here: https://github.com/lbialy/functionaljava8
Functional programming has started (re)gaining prominence in recent years, and with good reason too. Functional programs lend an elegant solution to the concurrency problem, result in more modular systems, are more concise and are easier to test. While modern languages like Scala and Clojure have embraced the functional style whole-heartedly, Java has lagged a bit behind in its treatment of functions as first-class citizens. With the advent of Java 8 and its support for lambdas, however, Java programmers can finally start reaping the power of functional programs as well. Even without Java 8, it is possible to adopt a functional style with the aid of excellent libraries such as Guava.
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
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...
Introduction to functional idioms in Java 8, language-extending functional libraries and short overview of reasons for adoption of such programming style.
Examples and snippets available here: https://github.com/lbialy/functionaljava8
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
This presentation provides an overview of oracle's associate and professional Java certifications - gives you ideas on how to prepare and crack the exam with ease.
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
If you are preparing to appear for Oracle Certified Professional Java SE 8 Programmer (OCPJP 8) certification exam, this a reference card (sort of long cheat sheet) meant to help you. You may want to print this reference card for your easy and quick reference when you prepare for your exam.
- Highlight the performance benefits of using Java 8 - after all, you’ll probably have to persuade "The Management" that tampering with
existing code is worthwhile
- Demonstrate how to identify areas of code that can be updated to use Java 8 features, and how to pick which changes will give you the
most benefit
- Demonstrate how to automatically refactor your code to make use of features like lambdas and streams
- Cover some of the pros and cons of using the new features - including suggestions of when refactoring may NOT be the best idea.
Slides from my JAX London 2016 talk, discussing how the new features affect library design. Follows on from the Java SE 8 Best Practices talk - http://www.slideshare.net/scolebourne/java-se-8-best-practices-53975908
At least since the release of Java 8, functional programming has become mainstream in the Java community. Things like collection processing, lazy evaluation and concurrent programming are much easier to describe in a functional style than in the traditional procedural or object-oriented way.
Xtend is a Java dialect hosted at Eclipse. Designed to remove the syntactic noise, it offers a superior syntax and additional abstractions to provide the full power of functional programming to Java developers. As it compiles to Java 5 code, it will enable functional programming even for Android and GWT developers.
In this tutorial, you will learn the basic principles of functional programming and the Xtend idioms to write code the functional way: concise, easy to understand, and yet powerful. No prior knowledge of functional programming or Xtend required.
Lambda: A Peek Under The Hood - Brian GoetzJAX London
This is a *highly technical* session on the details of how Lambda expressions are implemented in the Java language, presented by Java Language Architect Brian Goetz
The objectives of the seminar are to shed a light on the premises of FP and give you a basic understanding of the pillars of FP so that you would feel enlightened at the end of the session. When you walk away from the seminar you should feel an inner light about the new way of programming and an urge & motivation to code like you never before did!
Functional programming should not be confused with imperative (or procedural) programming. Neither it is like object oriented programming. It is something different. Not radically so, since the concepts that we will be exploring are familiar programming concepts, just expressed in a different way. The philosophy behind how these concepts are applied to solving problems are also a little different. We shall learn and talk about essentially the fundamental elements of Functional Programming.
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
This presentation provides an overview of oracle's associate and professional Java certifications - gives you ideas on how to prepare and crack the exam with ease.
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
If you are preparing to appear for Oracle Certified Professional Java SE 8 Programmer (OCPJP 8) certification exam, this a reference card (sort of long cheat sheet) meant to help you. You may want to print this reference card for your easy and quick reference when you prepare for your exam.
- Highlight the performance benefits of using Java 8 - after all, you’ll probably have to persuade "The Management" that tampering with
existing code is worthwhile
- Demonstrate how to identify areas of code that can be updated to use Java 8 features, and how to pick which changes will give you the
most benefit
- Demonstrate how to automatically refactor your code to make use of features like lambdas and streams
- Cover some of the pros and cons of using the new features - including suggestions of when refactoring may NOT be the best idea.
Slides from my JAX London 2016 talk, discussing how the new features affect library design. Follows on from the Java SE 8 Best Practices talk - http://www.slideshare.net/scolebourne/java-se-8-best-practices-53975908
At least since the release of Java 8, functional programming has become mainstream in the Java community. Things like collection processing, lazy evaluation and concurrent programming are much easier to describe in a functional style than in the traditional procedural or object-oriented way.
Xtend is a Java dialect hosted at Eclipse. Designed to remove the syntactic noise, it offers a superior syntax and additional abstractions to provide the full power of functional programming to Java developers. As it compiles to Java 5 code, it will enable functional programming even for Android and GWT developers.
In this tutorial, you will learn the basic principles of functional programming and the Xtend idioms to write code the functional way: concise, easy to understand, and yet powerful. No prior knowledge of functional programming or Xtend required.
Lambda: A Peek Under The Hood - Brian GoetzJAX London
This is a *highly technical* session on the details of how Lambda expressions are implemented in the Java language, presented by Java Language Architect Brian Goetz
The objectives of the seminar are to shed a light on the premises of FP and give you a basic understanding of the pillars of FP so that you would feel enlightened at the end of the session. When you walk away from the seminar you should feel an inner light about the new way of programming and an urge & motivation to code like you never before did!
Functional programming should not be confused with imperative (or procedural) programming. Neither it is like object oriented programming. It is something different. Not radically so, since the concepts that we will be exploring are familiar programming concepts, just expressed in a different way. The philosophy behind how these concepts are applied to solving problems are also a little different. We shall learn and talk about essentially the fundamental elements of Functional Programming.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
The main features of java is; It is object oriented programming language. It is also simple and easy to learn. Java is platform independent programming language. These above are main features of java.
https://www.sitesbay.com/java/features-of-java
Java 8 supports lambdas. It's API also comes with Streams support.
But Knowing some concepts on Functional Programming may help you get a lot more from what this new version of Java has to offer.
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 chapter covers:
- The most common approaches to program design and development
- The phases of the program development life cycle (PDLC)
- Tools that can be used to design and develop a program
- Good program design techniques and types of program errors
- Common programming languages
Functional Programming in Java - Code for MaintainabilityMarcin Stepien
Functional Programming is nothing new to the JVM. But with Java 8 it was the big change in paradigm for Java developers. Learn how switching from imperative to functional results in more maintainable code.
The presentation was given at tech meetup KrkDataLink, The missing link between Functional Programming and Data Science.
Why C is Called Structured Programming LanguageSinbad Konick
This Slide was made for a presentation based on the Topic Why C is Called Structured Programming Language . So here we added some history about C Programming from where did it came from , who invented it . What does structured programming actually means . And finally the advantage and disadvantage of C Programming . Future of C Programming .
Functional Programming for OO Programmers (part 1)Calvin Cheng
The Why and Benefits of Functional Programming paradigm. Part 2 with source code can be found here: http://www.slideshare.net/calvinchengx/functional-programming-for-oo-programmers-part-2
Related source code https://github.com/calvinchengx/learnhaskell
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples and demos for all cases discussed will be added to my blog www.javajee.com.
You’re finally doing TDD, but your past mistakes are catching up with you. No matter what you do, you can’t get rid of the gaping black holes caused by your legacy code.
In this presentation, we learn about the causes of legacy code and the reasons it is so difficult to work with. Then we discuss various techniques to test untestable code, revive and simplify incomprehensible code, redesign stable yet untested code, and repair that rift we created in the time-space continuum.
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.
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
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.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
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.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
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
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/
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
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.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
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.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
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!
7. • A programming paradigm where
functions are first-class entities
• The main concepts are:
1. programming with functions
2. avoid mutation
• A new way of thinking
WHAT IS FP ?
8. • Object Immutability
• Functions:
– as first class citizens
– no side effects (Pure functions)
– Higher Order Functions
• No loops
• Lazy evaluation
WHAT IS FP ? / FUNCTIONAL PRINCIPLES
9. • Easier parallelization
• Less code
• Easy testing
• Results instead of steps
• Easy to understand code
WHAT IS FP ? / WHAT YOU GET ?
12. An immutable object is an object
whose state cannot be modified
after it is created
IMMUTABLE OBJECTS
13. “Classes should be immutable unless
there’s very good reason to make them
mutable… If a class cannot be made
immutable, limit its mutability as much
as possible”
Joshua Bloch
IMMUTABLE OBJECTS
30. •Allows easy parallelism
•Encourages abstraction
•Reusing of common code
•Isolates the essential parts
•Allows easier unit testing
HIGHER ORDER FUNCTIONS
35. HIGHER ORDER FUNCTIONS / LAMBDA EXPRESSIONS
• A lambda expression is an anonymous
method
• Lambdas favor HOFs
• more powerful libraries
• more expressive, more readable, less
error-prone use code
• Boosts developer productivity
• key to an accessible parallelism strategy
44. A function is said to be pure if
1. it returns same set of values
for same set of inputs
2. It does not have any
observable side effects
PURE FUNCTIONS / DEFINITION
47. Impure functions / Side effects :
1. Alter parameters passed by ref
2. Alter members of passed
objects
3. Alter external objects
PURE FUNCTIONS / SIDE EFFECTS
68. NO LOOPS / FUNCTION CHAINING
• Similar to unix pipes :
ps -ax | tee processes.txt | more
• Already used in java in fluent interfaces
• Eliminate the need for intermediate variables
69. NO LOOPS / FUNCTION CHAINING
persons.stream()
.filter(e -> e.getGender() == Person.Sex.MALE)
.forEach(e -> System.out.println(e.getName()));
for (Person p : persons) {
if (p.getGender() == Person.Sex.MALE) {
System.out.println(p.getName());
}
}
70. NO LOOPS / AGGREGATE OPERATIONS
• They use internal iteration
• They process elements from a stream
• They support behavior as parameters
76. FUNCTIONS CHAINING / STREAMS IN JAVA 8
• Streams do not provide a means to directly access or
manipulate their elements
• are concerned with declaratively describing the
computational operations which will be performed in
aggregate on that source
• No storage: they carry values from a source through a
pipeline
• Functional in nature ( operations do not modify its
underlying data)
• Operations can be implemented lazily ( for single pass
execution & efficient implementation of short-circuit
operations)
• No bounds : streams can be infinite
86. OPTIONAL / NULL, THE BILLION DOLLAR MISTAKE
"I call it my billion-dollar mistake. It was the invention of the
null reference in 1965. […]
I couldn't resist the temptation to put in a null reference,
simply because it was so easy to implement.
This has led to innumerable errors, vulnerabilities, and system
crashes, which have probably caused a billion dollars of pain
and damage in the last forty years“
Tony Hoare
87. OPTIONAL / THE SOLUTION TO NULL
java.util.Optional<T> :
• A class that encapsulates an optional value
• A single-value container that either contains
a value or doesn't (empty)
Ce ne propunem ?
Prezentarea este destul de ambitioasa pentru ca ataca doua tinte: functional programming si java8 most important features.
Focusul va fi pe FP.
Disclaimer:
- codul in F#
The evolution of the clock speed over time.
Unul din factorii care contribuiau la imbunatatirea puterii de calcul si-a oprit cresterea.
Este prima data cand legea lui Moore este pusa sub semnul intrebarii.
Hardware-ul se schimba -> software-ul tre’ sa se schimbe pentru a tine pasul.
Articol: The free lunch is over :
- processor manufacturers will focus on products that better support multithreading (such as multi-core processors)
- software developers will be forced to develop massively multithreaded programs as a way to better use such processors
(i.e: proasta calitate a codului, nu mai poate fi acoperita de imbunatatirea vitezei de calcul)
Codul nostru va rula distribuit intre core-urile procesorului.
Evolutia limbajelor de programare.
A se nota faptul ca limbajele functionale au aparut cu mult inaintea limbajelor OOP.
Principiile din limbajele functionale se mapeaza mult mai bine pe ideea de multi threading / paralelism.
Principiile FP derivate din cele doua concepte prezentate anterior
Easier parallelization != No work for parallelization
Results instead of steps -> SQL
Verbe in locul substantivelor
Imutabilitatea nu e ceva nou.
Este recomandata si-n OOP.
No setters
Final fields
Final class
Java examples ?
Un exemplu mai complex.
Unul din campurile clasei este mutabil.
Ultima metoda returneaza o copie defensiva pentru a evita mutabilitatea.
Exemplu de clasa imutabila in Scala.
Exemplu de clasa imutabila in F#.
Pentru a face un obiect mutabil trebuie utilizat cuvantul cheie “mutable”
Talk about the memory consumption and the extra work to be done by the garbage collector.
Extrapolate the example above to lists, trees, etc.
Other benefits:
- don't need a copy constructor
- don't need an implementation of clone
- allow hashCode to use lazy initialization, and to cache its return value
- don't need to be copied defensively when used as a field
- make good Map keys and Set elements (these objects must not change state while in the collection)
- always have "failure atomicity" : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
In loc de obiectul rational de mai devreme sa ne gandim ca avem o lista.add
Garbage collection: ok atata timp cat nu lucrezi la Twitter.
This cannot be achieved in Java but … talk about the new functional interfaces ; Predicate, Filter, …
HOFs can be assigned to variables
HOFs can be created at runtime and used
Functions are just as any other data types
Sum accepts another function as input parameter
higherOrderFunction returns a function as a result
Functions as first class citizens
Functions as parameters
Functions as return values
sumOfSquares -> easy abstraction –> sum (f)
Easy parallelism
A new package added in java8
In java everything is a class -> functions are classes
The most important java classes in the java.util.function package
All introduced in Java8
Cam asa am fi utilizat clasele in Java 7
Note the lambda expression
No boilerplate
Explain the type inference
Remember the anonymous classes in java
Examples with the most important classes implemented as lambda expressions
Cum acoperim toate situatiile ? Prin annotation : FunctionalInterface
A functional interface has only one abstract method.
Instances of functional interfaces can be created with lambda or method references
This is how we use the Functional Interface annotation.
Note: the lambda expression used to define an anonymous definition of a Functional Interface
Cum utilizam metodele deja existente ?
De observat referintele la metodele din clasele Math, Integer.
HOF
Lambda
Function references
Pure functions = No side effects
Impure function - has side effects
Impure function -> it doesn’t return the same values for the same inputs
Sin = pure
Length = pure
Random() = impure
Println() = impure
SQL Insert = impure
Easier to maintain: devs spend less time analyzing the impact
Once tested all edge conditions we can be sure that the function behaves correctly
Easy concurency: see next side/example
No side effects favorizeaza paralelismul
The same input -> same output favorizeaza testarea si intelegerea
Any write to the console is a side-effect.
Database updates or file writes on disk is a side-effect.
So we cannot be 100% pure but the goal is to be as pure as possible.
In an input – process– output flow the goal is to keep the middle (process) functional.
g o f (c) = #
Metodele compose si andThen
Pure functions
Function composition
HOF
Lambdas
Function references
What is the problem ?
Incurajeaza shared state (variabilele partajate) = nu bine pt. paralelism
Mult boilerplate
Why avoid loops ?
boilerplate code
Incurajeaza partajarea state-ului deci nu este prietenos cu multi-threadingul.
In some cases ( most of them ? ) recursion is more intuitive then iteration.
Functional languages have better implementations for recursion
For OOP languages iteration is much faster than recursion
The mantra of functional languages: CLARITY TRUMPS EFFICIENCY (preferam claritatea vs. eficienta)
the function’s stack frame can be reused.
Remember stiva de executie a unei functii.
After the call to factorial(n-1) there is still work to be done => not a tail recursive action
Note: Since the stack trace is optimized, when printing the stack trace one will only see the last call instead of the entire stack trace.
Functional languages have better support for recursion (see the list.head, list.tail)
This is not possible with all lists in idiomatic java.
Function chaining = Un caz particular de compozitie
To be discussed here:
Imperative approach vs. Functional approach :
For vs. map-reduce
State vs. stateless
Discussion about state / share state ( in a multi-threaded env.) : let’s sum the salaries of males in a multi-threaded env.
Func. Chaining can be seen as a particular case of composition.
Discussion about state / share state ( in a multi-threaded env.) : let’s sum the salaries of males in a multi-threaded env.
Func. Chaining can be seen as a particular case of composition.
Note the chaining of combinator methods : map, filter, reduce/foldLeft
The same functionality in Java8.
Imperative vs. Declarative style / Ce face functia vs. Cum face functia / The SQL Example.
Note 1: the stream() method
Note 2: a method added to a the list interface (DEFAULT METHODS discussion)
Discussion about map/filter/reduce
We’ll come back to map/reduce/filter in a few moments
The average age of males in the persons list.
When using streams we need the following components:
1 A source ( list )
2.Zero or more intermediate operations ( filters, transformers)
3. A terminal operation ( average)
Default Method Discussion
2. Stream interface
The Stream interface and the map / reduce methods
Streams cannot be reused.
Please check the Stream javadoc .
http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps
The stream could have been infinite
I could have used only lambdas
Note the findFirst method returning an optional (discussed later in this material)
Re-start the map/reduce discussion
Reduce needs to be associative
(a+b)+c = a+(b+c), i.e. the order in which the additions are performed doesn't matter.
How sequential reduce works.
Free parallelism but this doesn’t happen every time
Sum() is a particular form of reduce() – a shortcut for reduce(0, (a,b) -> a+b)
reduce, collect, sum = terminal methods
Note: Order of filtering matters
Note: the operation has to be associative otherwise the result will not be consistent (no compilation or runtime error)
Example of a non associative operation: x*x + y*y
Discussion about non-associative
Disclaimer: the table shows the test results in ideal conditions ( no other threads were running) - in production systems you won’t get this kind of difference
The power of collectors
The problem with null: Depending on the context, null means “no value”, other times it means “error” or “nothing”, but it can even mean “success”
Optional is inspired from Haskel and Scala
Idiot proof : It forces you to actively think about the absent case if you want your program to compile
There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception
Functional programming = no loops
Recursivitate
Function chaining
Function composition
Streams
Map / reduce
Default methods
Optional
Functional programming = no loops
Recursivitate
Function chaining ( this is also related to composition)
Streams
Map / reduce
Lambda instead of a Runnable
Runnable este o interfata functionala
Lambda instead of an Action Listener
Lambda instead of a Comparator.
Why the Users type has been specified ? - where is the type inference ?
Method reference in a forEach method
BufferedReader.lines() returns a Stream
Files.lines() returns a Stream as well. The examples shows how to use the stream in a try-with-resources ( it implements AutoClosable).
Spring jdbc template with lambda expressions ( instead of RowMapper.mapRow(ResultSet, int rowNum)
Outside the scope :
Advanced Laziness
Monads
Function currying
Outside the scope :
Java8
------------------------------------
Type Annotations
Date and time API
Lambda translation to bytecode
Nashorn Javascript engine
Easier parallelization != No work for parallelization
What instead of How
Verbe in loc de substantive
Some non-programming mistakes have been intentionally inserted into the presentation
Responsive: The system responds in a timely manner
Resilient: The system stays responsive even in failure
Elastic: The service allocates resources as needed ( according to the workload)
Message Driven: Async message passing for loose coupling, isolation, transparency