SlideShare a Scribd company logo
Intro to Java 8
Part 1 - Functional Programming, Lambda and Stream
-
John Henrique Teixeira de Godoi
@john_godoi
References
● Java 8 Prático - Paulo Silveira, Rodrigo Turini - Casa do Código - 2014
● Oracle Certified Associate Java SE 8 Programmer I Study Guide - Jeanne
Boyarsky, Scott Selikoff - Sybex - 2015
● Oracle Certified Professional Java SE 8 Programmer II Study Guide - Jeanne
Boyarsky, Scott Selikoff - Sybex - 2016
● Slides from Functional Programming with Scala - Martin Odersky - Coursera
Brief
Review
Interfaces, Abstract Classes, Anonymous Classes & Reflection
Static methods and variables
Static methods and variables
● What means to be static?
● How do you use static:
○ Methods?
○ Variables?
● Should you use static variables? Why?
○ If it is final is there any difference?
Abstract Classes
Abstract Classes
● What is the purpose?
● What is necessary?
○ Can an abstract class not have an abstract method?
○ Can an abstract method not be in an abstract class?
● How many abstract methods can we have?
Interfaces
Interfaces
● What is the purpose of an interface in Java?
● Can we have implementation of methods in an interface? Why?
● Can we have variables in an interface? Should we?
Anonymous Classes
Anonymous Classes
● What is the purpose?
● How do you normally use?
● Is there any rules about its use? Can I use any variable inside?
● Here is most of the lambda’s secret!!!!
Reflection (No, it ain’t about meditation!)
Reflection (No, it ain’t about meditation!)
● Ability of the code inspect and change itself.
● It is not a requirement to learn functional programming in Java but it helps!
Paradigms
Object Oriented & Functional
Object-Oriented
Unit: Object/Class
● Encapsulation
● Polymorphism
● Inheritance
● Abstraction
● Objects interact with each other
by methods organized in
modules
Functional
Programming
Unit: function
● Based in the math philosophy
● No mutable variables, no
assignments, no imperative
control structures
● Focus on function
○ Defined anywhere
○ Function as parameter or return
value
○ Operators for functions
Functional
Programming
in Java
How?
● Object Oriented of course! (Keep that in mind!)
○ Behinds the Java functional features there are interfaces like Function, Consumer, Predicate and
Supplier
● JVM can infer the type
○ Received improvements at Java 8
● “You specify what you want to do rather than dealing with the state of objects.
You focus more on expressions than loops.”
Functional Interfaces
● They contains just one abstract method
○ Any interface with just one abstract method is functional
● You can use any the @FunctionalInterface to check in compile time if the
interface attends this requirement
Functional Interfaces
Functional Interfaces
Functional Interfaces
ƛ
● Lambdas expressions comes to
Java 8 to allow functional
programming.
● With it is possible:
○ Implement anonymous functions
“anywhere”
○ Pass those functions as parameters
and return
● It can be used with all sort of
functional interfaces
lambda
lambda
lambda
Default Methods
● Functional Interface can only have an abstract method.
Default Methods
● Functional Interface can only have an abstract method.
● What if you want to add an implementation method instead of another abstract
one?
Default Methods
● Functional Interface can only have an abstract method.
● What if you want to add an implementation method instead of another abstract
one?
○ WAIT! Interfaces can’t have implementation methods!
Default Methods
● Functional Interface can only have an abstract method.
● What if you want to add an implementation method instead of another abstract
one?
○ WAIT! Interfaces can’t have implementation methods!
■ Right! But just till Java 8!
■ In Java 8 they added the feature called as default method.
Default Methods
● Functional Interface can only have an abstract method.
● What if you want to add an implementation method instead of another abstract
one?
○ WAIT! Interfaces can’t have implementation methods!
■ Right! But just till Java 8!
■ In Java 8 they added the feature called as default method.
● Default methods allows you declare an implementation method in the interface
using the modifier default before the method.
Default Methods
Default Methods
Time for a break…
Improvements
to Collection
API
Methods added
● Some improvements were made to Collection API adding:
○ forEach method to Iterable interface
■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements
forEach method
Methods added
● Some improvements were made to Collection API adding:
○ forEach method to Iterable interface
■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements
○ removeIf method to Collection interface
■ Remove all the items that matchs to the Predicate
removeIf method
Methods added
● Some improvements were made to Collection API adding:
○ forEach method to Iterable interface
■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements
○ removeIf method to Collection interface
■ Remove all the items that matchs to the Predicate
○ sort method to List interface
■ Sort items in a collection by a lambda expression for Comparator
sort method
Methods added
● Some improvements were made to Collection API adding:
○ forEach method to Iterable interface
■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements
○ removeIf method to Collection interface
■ Remove all the items that matchs to the Predicate
○ sort method to List interface
■ Sort items in a collection by a lambda expression for Comparator
○ replaceAll method to List interface
■ Replace the items by the result of applying a lambda expression for UnaryOperator
replaceAll method
Methods added
● Some improvements were made to Collection API adding:
○ forEach method to Iterable interface
■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements
○ removeIf method to Collection interface
■ Remove all the items that matchs to the Predicate
○ sort method to List interface
■ Sort items in a collection by a lambda expression for Comparator
○ replaceAll method to List interface
■ Replace the items by the result of applying a lambda expression for UnaryOperator
○ stream and parallelStream methods to Collection interface
■ Those methods are factory methods that create a Stream or a ParallelStream from a
Collection
Streams
Streams
Streams
● A functional version of collection
○ Immutable
○ Process data all at once
○ Naturally thread-safe
○ Disposable
○ Fluent API
Streams
To be continued...
Avaliação: https://goo.gl/forms/DJYEDDbUhecRbZul2
Intro to Java 8
Part 2 - More Stream
-
John Henrique Teixeira de Godoi
jgodoi@fitec.org.br
@john_godoi
The road so
far...
Functional Interfaces
Lambda & Default Methods
Collection API Improvements
Now
More Stream!
Streams
● Operations at a stream can be:
○ Intermediate
■ Can be more than one in a pipeline
■ Return type is a stream type
■ Stream still valid after call
■ Lazy execution
■ Ex.: filter(), sorted(), map()
Streams
● Operations at a stream can be:
○ Intermediate
■ Can exist multiple time in a pipeline
■ Return type is a stream type
■ Stream still valid after call
■ Lazy execution
■ Ex.: filter(), sorted(), map()
○ Terminal
■ Required part of a useful pipeline
■ Executed upon method call
■ Ex.: forEach()
Streams
● forEach
lyric.stream().forEach(line -> System.out.println(line));
● filter
lyric.stream().filter(line -> !line.isEmpty()).forEach(line ->
System.out.println(line));
● sort
lyric.stream().map(line -> line.toUpperCase()).forEach(line ->
System.out.println(line));
● map
lyric.stream().sorted().forEach(line -> System.out.println(line));
lyric.stream().sorted(Comparator.reverseOrder()).forEach(line ->
System.out.println(line));
The creation of Java
1. The JVM was without types and there was just void. So, Gosling came and said let
there be primitives. Then appeared int, long, char, float, double and others.
The creation of Java
1. The JVM was without types and there was just void. So, Gosling came and said let
there be primitives. Then appeared int, long, char, float, double and others.
2. From the declarative chaos Gosling made the Object. It would domain everything
in the JVM. Gosling seeing the Object alone and without definition, he decide to
create the Class. From their union others objects could be instantiated and
defined to populate the memory. And Gosling saw that was good.
The creation of Java
1. The JVM was without types and there was just void. So, Gosling came and said let
there be primitives. Then appeared int, long, char, float, double and others.
2. From the declarative chaos Gosling made the Object. It would domain everything
in the JVM. Gosling seeing the Object alone and without definition, he decide to
create the Class. From their union others objects could be instantiated and
defined to populate the memory. And Gosling saw that was good.
3. Then Gosling created also classes for the primitives (Integer, Long, Character,
Float, Double and others), so them could instantiate objects too. To those classes,
he called them as Wrappers. A primitive could turn into a object of its Wrapper
automatically, and vice-versa. That came to be known as autoboxing.
autoboxing
Wickedness in the Runtime
1. The objects began to increase in number. And autoboxing was being used all the
time. So, things started to make the runtime out of control and slow.
Wickedness in the Runtime
1. The objects began to increase in number. And autoboxing was being used all the
time. So, things started to make the runtime out of control and slow.
2. One prophet of Gosling, Bloch, with the Effective book proclaimed that, because
of the time consuming in massive processing, autoboxing should be avoided
always as possible.
Wickedness in the Runtime
1. The objects began to increase in number. And autoboxing was being used all the
time. So, things started to make the runtime out of control and slow.
2. One prophet of Gosling, Bloch, with the Effective book proclaimed that, because
of the time consuming in massive processing, autoboxing should be avoided
always as possible.
3. Collection API is based in Objects and doesn’t support primitives.
Wickedness in the Runtime
1. The objects began to increase in number. And autoboxing was being used all the
time. So, things started to make the runtime out of control and slow.
2. One prophet of Gosling, Bloch, with the Effective book proclaimed that, because
of the time consuming in massive processing, autoboxing should be avoided
always as possible.
3. Collection API is based in Objects and doesn’t support primitives.
And now… Who could help us?
IntStream and the
Stream Family
mapToInt
● Using map function to create a stream of integers probably:
Stream<Integer> integerStream = units.stream().map(unit ->
unit.getConsume());
● That uses autoboxing and has potential to become a time consuming problem.
One way to avoid it, is using the mapToInt version.
IntStream intStream = units.stream().mapToInt(unit -> unit.getConsume());
Another way to
look at streams ● The sintaxe of Stream API looks
like SQL queries.
● And its concept as well.
reductions
● Reductions are terminal operations that reduces ALL the data to one just one
value result
● This result can be Optional
reductions
● max
OptionalInt max = units.stream().mapToInt(unit -> unit.getAttack()).max();
● min
OptionalInt min = units.stream().mapToInt(unit -> unit.getAttack()).min();
reductions
● sum
int sum = units.stream().mapToInt(unit -> unit.getAttack()).sum();
● count
long count = units.stream().count();
● average
OptionalDouble average = units.stream().mapToInt(unit ->
unit.getAttack()).average();
reductions
● reduce
int totalAttack = units.stream().mapToInt(unit ->
unit.getAttack()).reduce(0, (combined, attack) -> combined + attack);
Integer alsoTotalAttack = units.stream().reduce(0, (result, unit) ->
result + unit.getAttack(), (combined, actual) -> combined + actual);
summaryStatistics
● This class will give you some statistics about your numeric stream
IntSummaryStatistics summaryStatistics = units.stream().mapToInt(unit ->
unit.getAttack()).summaryStatistics();
System.out.println(summaryStatistics);
// IntSummaryStatistics{count=25, sum=150, min=2, average=6,000000,
max=10}
find methods
● The find methods returns an element with the stream is not empty. But if the
stream is empty, it return an Optional value.
find methods
● The find methods returns an element with the stream is not empty. But if the
stream is empty, it return an Optional value.
● findFirst() - return the “real” first element on the list
Optional<Unit> firstPeon = units.stream().filter(u -> u instanceof
Peon).findFirst();
find methods
● The find methods returns an element with the stream is not empty. But if the
stream is empty, it return an Optional value.
● findFirst() - return the “real” first element on the list
Optional<Unit> firstPeon = units.stream().filter(u -> u instanceof
Peon).findFirst();
● findAny() - return the first element on the list
Optional<Unit> anyAlive = units.parallelStream().filter(u -> u.getEnergy()
> 0).findAny();
matchs
● The match methods analyse the stream data and tell whether a predicate is valid
or not
matchs
● allMatch() - looks through ALL the data whether them match to the predicate
boolean allMatch = units.stream().allMatch(unit -> unit instanceof Unit);
matchs
● allMatch() - looks through ALL the data whether them match to the predicate
boolean allMatch = units.stream().allMatch(unit -> unit instanceof Unit);
● anyMatch() - looks through the data whether any match to the predicate, if
positive return the first to match and stops processing
boolean anyMatch = units.stream().anyMatch(unit -> unit instanceof
Healer);
matchs
● allMatch() - looks through ALL the data whether them match to the predicate
boolean allMatch = units.stream().allMatch(unit -> unit instanceof Unit);
● anyMatch() - looks through the data whether any match to the predicate, if
positive return the first to match and stops processing
boolean anyMatch = units.stream().anyMatch(unit -> unit instanceof
Healer);
● noneMatch() - looks through ALL the data checking if none of them match to the
predicate
boolean noneMatch = units.stream().noneMatch(unit -> unit instanceof
Hero);
Optional
● Some operations can have an unexpected result or no result at all.
Optional
● Some operations can have an unexpected result or no result at all.
● You could use null to those cases but it comes with more problems than solutions.
Optional
● Some operations can have an unexpected result or no result at all.
● You could use null to those cases but it comes with more problems than solutions.
● In those case, you may also want a default value or an object that helps to
determine that those cases occurred.
Optional
● Some operations can have an unexpected result or no result at all.
● You could use null to those cases but it comes with more problems than solutions.
● In those case, you may also want a default value or an object that helps to
determine that those cases occurred.
● So since Java 8, “If you want Optional, you got it!”
Optional
● Some operations can have an unexpected result or no result at all.
● You could use null to those cases but it comes with more problems than solutions.
● In those case, you may also want a default value or an object that helps to
determine that those cases occurred.
● So since Java 8, “If you want Optional, you got it!”
● And it comes in others flavors: OptionalInt, OptionalLong e OptionalDouble
Optional
● Optional class offers:
Optional
Time for a break…
Limit, skip, distinct
● The limit() and skip() makes a Stream smaller
○ skip returns a stream without the first elements, the quantity is specified by parameter
Stream<Unit> saveTheFirstThree = units.stream().skip(10);
Limit, skip, distinct
● The limit() and skip() makes a Stream smaller
○ skip returns a stream without the first elements, the quantity is specified by parameter
Stream<Unit> saveTheFirstThree = units.stream().skip(10);
○ limit returns just a stream with the first elements, the quantity is specified by parameter
saveTheFirstThree.limit(5).forEach(unit -> System.out.println(unit));
Limit, skip, distinct
● The limit() and skip() makes a Stream smaller
○ skip returns a stream without the first elements, the quantity is specified by parameter
Stream<Unit> saveTheFirstThree = units.stream().skip(10);
○ limit returns just a stream with the first elements, the quantity is specified by parameter
saveTheFirstThree.limit(5).forEach(unit -> System.out.println(unit));
● The distinct method removes all the duplicates
units.stream().map(unit ->
unit.getClass().getSimpleName()).distinct().forEach(name ->
System.out.println(name));
Reference Method
● Let’s say that is just another way to create a lambda
Reference Method
● Let’s say that is just another way to create a lambda
● When you want to create a lambda with just one call to a method, you could just
use a reference for this method
Reference Method
● Let’s say that is just another way to create a lambda
● When you want to create a lambda with just one call to a method, you could just
use a reference for this method
● Calling a method from each instance
double averageSpeed =
units.stream().mapToInt(Unit::getSpeed).average().getAsDouble();
● Receiving each instance as argument
units.stream().forEach(System.out::println);
Collectors
● Can we obtain a collection back from a stream?
● Yes, we can!
Collectors
● Can we obtain a collection back from a stream?
● Yes, we can!
● At stream there are a method called collect() it receives a implementation for
Collector, that will tell how to create the collection, and return the collection with
the elements of the stream inside.
Collectors
● Can we obtain a collection back from a stream?
● Yes, we can!
● At stream there are a method called collect() it receives a implementation for
Collector, that will tell how to create the collection, and return the collection with
the elements of the stream inside.
● Also, there is a Collectors class that wraps those implementations.
○ You can passa just a call for one of its methods to collect()
units.stream().filter(unit -> unit.getAttack() > 0).collect(Collectors.toList());
Grouping
● Sometimes you may want to classify the elements of a stream by some features
● For that you could make groups of them by values of the selected features
● groupingBy a feature will result in a map
Map<String, List<Unit>> unitsByType =
units.stream().collect(Collectors.groupingBy(unit ->
unit.getClass().getSimpleName()));
Partitioning
● groupingBy a boolean feature has a specific method partitioningBy
Map<Boolean, List<Unit>> strongers =
units.stream().collect(Collectors.partitioningBy(unit -> unit.getAttack()
>= 10));
System.out.println(strongers.get(true));
System.out.println(strongers.get(false));
Comparator
● Since 8th version of Java, the Comparator interface is functional.
units.sort(Comparator.comparing(Unit::getAttack));
● Beyond that some default methods were added to this interface with some
commons uses. These methods can be called chaining the calls.
units.sort(Comparator.comparing(Unit::getAttack).thenComparing(unit ->
unit.getClass().getSimpleName()));
Avaliação: https://goo.gl/forms/0KU12lB0eYDhKudg1
What we have done?
● Reviews of Java SE
● Functional Programming
● Functional Interfaces
● Default Methods
● lambda
● Streams till exhaustion (Still have more to cover!)
● Optional
● Reference Method
● Collectors
● Comparators
Challenge #1
● Create an abstract class called
Creator
● Creator will have a static method
create that receives any Class
that implements an interface
Creature and return an instance
of it
● The create implementation
should go inside an Thread
Challenge #2
● Create an interface
Tekpix with
○ A default method
startComercial that will
return a greeting message
○ An abstract method
whatItDoes
Challenge #3
plantsAndWeeds = Arrays.asList("Camellias
7", "weed 5", "Sunflower 3", "Lily 1",
"weed 4", "Azalea 5", "weed 2", "Begonia
4");
● Remove all the weeds
● Increment the number after their
names by 1
● Sort by the number at the end in
decrescent order
● Print them without the numbers
Challenge #4 ● Convert challenge #3 to stream
Challenge #5 ● Who wants to be a millionaire?
● Figure out the statistics of
Bitcoin price dataset
Challenge #6
● From celebrities_profile.txt
○ Find the top 10 with more followers
○ Group them by gender
○ Sort by created_at
Bonus
Challenge ● Try to solve our Java challenge
at: https://bitbucket.org/dev-
fitec/desafiojavafitec
Intro to Java 8
Part 2 - More Stream
-
John Henrique Teixeira de Godoi
jgodoi@fitec.org.br
@john_godoi

More Related Content

PPTX
Comparing Golang and understanding Java Value Types
PDF
Hanoi JUG: Java 8 & lambdas
PDF
Object Oriented Programming : Part 2
PDF
Functional programming with Java 8
PPTX
Functional programming with Java 8
PPTX
Functional programming principles and Java 8
PDF
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
PDF
Functional Programming in Java
Comparing Golang and understanding Java Value Types
Hanoi JUG: Java 8 & lambdas
Object Oriented Programming : Part 2
Functional programming with Java 8
Functional programming with Java 8
Functional programming principles and Java 8
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
Functional Programming in Java

What's hot (20)

PPTX
Introduction to functional programming with java 8
PDF
OOPS Advanced
PPTX
Metaprogramming in Ruby
PDF
New c sharp4_features_part_v
PDF
Functional programming in scala
PPTX
Programming Paradigm & Languages
PPTX
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
PDF
Java 8 Lambda
PDF
Python Programming - III. Controlling the Flow
PDF
Lambdas in Java 8
PPTX
OCP Java (OCPJP) 8 Exam Quick Reference Card
PPTX
Functional programming for the Advanced Beginner
PDF
Applicative style programming
PPT
Functional OOP, Clojure style
PDF
FregeDay: Design and Implementation of the language (Ingo Wechsung)
PDF
Python for katana
PDF
Metaprogramming with javascript
PDF
Introduction to Kotlin - Android KTX
PDF
Maths&programming forartists wip
PDF
Grooming with Groovy
Introduction to functional programming with java 8
OOPS Advanced
Metaprogramming in Ruby
New c sharp4_features_part_v
Functional programming in scala
Programming Paradigm & Languages
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Java 8 Lambda
Python Programming - III. Controlling the Flow
Lambdas in Java 8
OCP Java (OCPJP) 8 Exam Quick Reference Card
Functional programming for the Advanced Beginner
Applicative style programming
Functional OOP, Clojure style
FregeDay: Design and Implementation of the language (Ingo Wechsung)
Python for katana
Metaprogramming with javascript
Introduction to Kotlin - Android KTX
Maths&programming forartists wip
Grooming with Groovy
Ad

Similar to Intro to java 8 (20)

PPTX
Java 8 - An Overview
PPTX
Java 8 Intro - Core Features
PPTX
A brief tour of modern Java
PPTX
PPTX
java150929145120-lva1-app6892 (2).pptx
DOCX
Colloquium Report
PPTX
The Road to Lambda - Mike Duigou
PPTX
Java 8 presentation
PDF
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
PPT
14274730 (1).ppt
PDF
Java 8-revealed
PPTX
Insight into java 1.8, OOP VS FP
PDF
PDF
Lambda Functions in Java 8
PDF
JSR 335 / java 8 - update reference
PPTX
Week-1..................................
PPTX
Java8: what's new and what's hot
PPTX
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
PPTX
Java 8
PDF
Java 8 - An Overview
Java 8 Intro - Core Features
A brief tour of modern Java
java150929145120-lva1-app6892 (2).pptx
Colloquium Report
The Road to Lambda - Mike Duigou
Java 8 presentation
Java 8 Interview Questions and Answers PDF By ScholarHat.pdf
14274730 (1).ppt
Java 8-revealed
Insight into java 1.8, OOP VS FP
Lambda Functions in Java 8
JSR 335 / java 8 - update reference
Week-1..................................
Java8: what's new and what's hot
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Java 8
Ad

More from John Godoi (15)

PDF
(5) maneiras de motivar a si mesmo
PDF
The Passionate Programmer (Career tips and learnings)
PDF
Spring boot
PDF
O jogo mental do poker
PDF
There is no box
PDF
Gimplabs2
PDF
Gimplabs3
PDF
PDF
Git básico
PDF
Gimplabs1
PDF
Shell Script
PDF
Comandos do Linux
PPTX
Introduction to apache spark
PPTX
Software craftsmanship
PDF
Java e orientação a objetos - aula 01
(5) maneiras de motivar a si mesmo
The Passionate Programmer (Career tips and learnings)
Spring boot
O jogo mental do poker
There is no box
Gimplabs2
Gimplabs3
Git básico
Gimplabs1
Shell Script
Comandos do Linux
Introduction to apache spark
Software craftsmanship
Java e orientação a objetos - aula 01

Recently uploaded (20)

PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Digital Strategies for Manufacturing Companies
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
L1 - Introduction to python Backend.pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
How to Migrate SBCGlobal Email to Yahoo Easily
Digital Strategies for Manufacturing Companies
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Upgrade and Innovation Strategies for SAP ERP Customers
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PTS Company Brochure 2025 (1).pdf.......
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
CHAPTER 2 - PM Management and IT Context
L1 - Introduction to python Backend.pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
How to Choose the Right IT Partner for Your Business in Malaysia
wealthsignaloriginal-com-DS-text-... (1).pdf
Odoo POS Development Services by CandidRoot Solutions
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
How Creative Agencies Leverage Project Management Software.pdf
Operating system designcfffgfgggggggvggggggggg
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)

Intro to java 8

  • 1. Intro to Java 8 Part 1 - Functional Programming, Lambda and Stream - John Henrique Teixeira de Godoi @john_godoi
  • 2. References ● Java 8 Prático - Paulo Silveira, Rodrigo Turini - Casa do Código - 2014 ● Oracle Certified Associate Java SE 8 Programmer I Study Guide - Jeanne Boyarsky, Scott Selikoff - Sybex - 2015 ● Oracle Certified Professional Java SE 8 Programmer II Study Guide - Jeanne Boyarsky, Scott Selikoff - Sybex - 2016 ● Slides from Functional Programming with Scala - Martin Odersky - Coursera
  • 3. Brief Review Interfaces, Abstract Classes, Anonymous Classes & Reflection
  • 4. Static methods and variables
  • 5. Static methods and variables ● What means to be static? ● How do you use static: ○ Methods? ○ Variables? ● Should you use static variables? Why? ○ If it is final is there any difference?
  • 7. Abstract Classes ● What is the purpose? ● What is necessary? ○ Can an abstract class not have an abstract method? ○ Can an abstract method not be in an abstract class? ● How many abstract methods can we have?
  • 9. Interfaces ● What is the purpose of an interface in Java? ● Can we have implementation of methods in an interface? Why? ● Can we have variables in an interface? Should we?
  • 11. Anonymous Classes ● What is the purpose? ● How do you normally use? ● Is there any rules about its use? Can I use any variable inside? ● Here is most of the lambda’s secret!!!!
  • 12. Reflection (No, it ain’t about meditation!)
  • 13. Reflection (No, it ain’t about meditation!) ● Ability of the code inspect and change itself. ● It is not a requirement to learn functional programming in Java but it helps!
  • 15. Object-Oriented Unit: Object/Class ● Encapsulation ● Polymorphism ● Inheritance ● Abstraction ● Objects interact with each other by methods organized in modules
  • 16. Functional Programming Unit: function ● Based in the math philosophy ● No mutable variables, no assignments, no imperative control structures ● Focus on function ○ Defined anywhere ○ Function as parameter or return value ○ Operators for functions
  • 18. How? ● Object Oriented of course! (Keep that in mind!) ○ Behinds the Java functional features there are interfaces like Function, Consumer, Predicate and Supplier ● JVM can infer the type ○ Received improvements at Java 8 ● “You specify what you want to do rather than dealing with the state of objects. You focus more on expressions than loops.”
  • 19. Functional Interfaces ● They contains just one abstract method ○ Any interface with just one abstract method is functional ● You can use any the @FunctionalInterface to check in compile time if the interface attends this requirement
  • 23. ƛ ● Lambdas expressions comes to Java 8 to allow functional programming. ● With it is possible: ○ Implement anonymous functions “anywhere” ○ Pass those functions as parameters and return ● It can be used with all sort of functional interfaces lambda
  • 26. Default Methods ● Functional Interface can only have an abstract method.
  • 27. Default Methods ● Functional Interface can only have an abstract method. ● What if you want to add an implementation method instead of another abstract one?
  • 28. Default Methods ● Functional Interface can only have an abstract method. ● What if you want to add an implementation method instead of another abstract one? ○ WAIT! Interfaces can’t have implementation methods!
  • 29. Default Methods ● Functional Interface can only have an abstract method. ● What if you want to add an implementation method instead of another abstract one? ○ WAIT! Interfaces can’t have implementation methods! ■ Right! But just till Java 8! ■ In Java 8 they added the feature called as default method.
  • 30. Default Methods ● Functional Interface can only have an abstract method. ● What if you want to add an implementation method instead of another abstract one? ○ WAIT! Interfaces can’t have implementation methods! ■ Right! But just till Java 8! ■ In Java 8 they added the feature called as default method. ● Default methods allows you declare an implementation method in the interface using the modifier default before the method.
  • 33. Time for a break…
  • 35. Methods added ● Some improvements were made to Collection API adding: ○ forEach method to Iterable interface ■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements
  • 37. Methods added ● Some improvements were made to Collection API adding: ○ forEach method to Iterable interface ■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements ○ removeIf method to Collection interface ■ Remove all the items that matchs to the Predicate
  • 39. Methods added ● Some improvements were made to Collection API adding: ○ forEach method to Iterable interface ■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements ○ removeIf method to Collection interface ■ Remove all the items that matchs to the Predicate ○ sort method to List interface ■ Sort items in a collection by a lambda expression for Comparator
  • 41. Methods added ● Some improvements were made to Collection API adding: ○ forEach method to Iterable interface ■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements ○ removeIf method to Collection interface ■ Remove all the items that matchs to the Predicate ○ sort method to List interface ■ Sort items in a collection by a lambda expression for Comparator ○ replaceAll method to List interface ■ Replace the items by the result of applying a lambda expression for UnaryOperator
  • 43. Methods added ● Some improvements were made to Collection API adding: ○ forEach method to Iterable interface ■ Allows to apply a function (lambda expression for Consumer), by lambda, into all elements ○ removeIf method to Collection interface ■ Remove all the items that matchs to the Predicate ○ sort method to List interface ■ Sort items in a collection by a lambda expression for Comparator ○ replaceAll method to List interface ■ Replace the items by the result of applying a lambda expression for UnaryOperator ○ stream and parallelStream methods to Collection interface ■ Those methods are factory methods that create a Stream or a ParallelStream from a Collection
  • 46. Streams ● A functional version of collection ○ Immutable ○ Process data all at once ○ Naturally thread-safe ○ Disposable ○ Fluent API
  • 48. To be continued... Avaliação: https://goo.gl/forms/DJYEDDbUhecRbZul2
  • 49. Intro to Java 8 Part 2 - More Stream - John Henrique Teixeira de Godoi jgodoi@fitec.org.br @john_godoi
  • 52. Lambda & Default Methods
  • 55. Streams ● Operations at a stream can be: ○ Intermediate ■ Can be more than one in a pipeline ■ Return type is a stream type ■ Stream still valid after call ■ Lazy execution ■ Ex.: filter(), sorted(), map()
  • 56. Streams ● Operations at a stream can be: ○ Intermediate ■ Can exist multiple time in a pipeline ■ Return type is a stream type ■ Stream still valid after call ■ Lazy execution ■ Ex.: filter(), sorted(), map() ○ Terminal ■ Required part of a useful pipeline ■ Executed upon method call ■ Ex.: forEach()
  • 57. Streams ● forEach lyric.stream().forEach(line -> System.out.println(line)); ● filter lyric.stream().filter(line -> !line.isEmpty()).forEach(line -> System.out.println(line)); ● sort lyric.stream().map(line -> line.toUpperCase()).forEach(line -> System.out.println(line)); ● map lyric.stream().sorted().forEach(line -> System.out.println(line)); lyric.stream().sorted(Comparator.reverseOrder()).forEach(line -> System.out.println(line));
  • 58. The creation of Java 1. The JVM was without types and there was just void. So, Gosling came and said let there be primitives. Then appeared int, long, char, float, double and others.
  • 59. The creation of Java 1. The JVM was without types and there was just void. So, Gosling came and said let there be primitives. Then appeared int, long, char, float, double and others. 2. From the declarative chaos Gosling made the Object. It would domain everything in the JVM. Gosling seeing the Object alone and without definition, he decide to create the Class. From their union others objects could be instantiated and defined to populate the memory. And Gosling saw that was good.
  • 60. The creation of Java 1. The JVM was without types and there was just void. So, Gosling came and said let there be primitives. Then appeared int, long, char, float, double and others. 2. From the declarative chaos Gosling made the Object. It would domain everything in the JVM. Gosling seeing the Object alone and without definition, he decide to create the Class. From their union others objects could be instantiated and defined to populate the memory. And Gosling saw that was good. 3. Then Gosling created also classes for the primitives (Integer, Long, Character, Float, Double and others), so them could instantiate objects too. To those classes, he called them as Wrappers. A primitive could turn into a object of its Wrapper automatically, and vice-versa. That came to be known as autoboxing.
  • 62. Wickedness in the Runtime 1. The objects began to increase in number. And autoboxing was being used all the time. So, things started to make the runtime out of control and slow.
  • 63. Wickedness in the Runtime 1. The objects began to increase in number. And autoboxing was being used all the time. So, things started to make the runtime out of control and slow. 2. One prophet of Gosling, Bloch, with the Effective book proclaimed that, because of the time consuming in massive processing, autoboxing should be avoided always as possible.
  • 64. Wickedness in the Runtime 1. The objects began to increase in number. And autoboxing was being used all the time. So, things started to make the runtime out of control and slow. 2. One prophet of Gosling, Bloch, with the Effective book proclaimed that, because of the time consuming in massive processing, autoboxing should be avoided always as possible. 3. Collection API is based in Objects and doesn’t support primitives.
  • 65. Wickedness in the Runtime 1. The objects began to increase in number. And autoboxing was being used all the time. So, things started to make the runtime out of control and slow. 2. One prophet of Gosling, Bloch, with the Effective book proclaimed that, because of the time consuming in massive processing, autoboxing should be avoided always as possible. 3. Collection API is based in Objects and doesn’t support primitives. And now… Who could help us?
  • 67. mapToInt ● Using map function to create a stream of integers probably: Stream<Integer> integerStream = units.stream().map(unit -> unit.getConsume()); ● That uses autoboxing and has potential to become a time consuming problem. One way to avoid it, is using the mapToInt version. IntStream intStream = units.stream().mapToInt(unit -> unit.getConsume());
  • 68. Another way to look at streams ● The sintaxe of Stream API looks like SQL queries. ● And its concept as well.
  • 69. reductions ● Reductions are terminal operations that reduces ALL the data to one just one value result ● This result can be Optional
  • 70. reductions ● max OptionalInt max = units.stream().mapToInt(unit -> unit.getAttack()).max(); ● min OptionalInt min = units.stream().mapToInt(unit -> unit.getAttack()).min();
  • 71. reductions ● sum int sum = units.stream().mapToInt(unit -> unit.getAttack()).sum(); ● count long count = units.stream().count(); ● average OptionalDouble average = units.stream().mapToInt(unit -> unit.getAttack()).average();
  • 72. reductions ● reduce int totalAttack = units.stream().mapToInt(unit -> unit.getAttack()).reduce(0, (combined, attack) -> combined + attack); Integer alsoTotalAttack = units.stream().reduce(0, (result, unit) -> result + unit.getAttack(), (combined, actual) -> combined + actual);
  • 73. summaryStatistics ● This class will give you some statistics about your numeric stream IntSummaryStatistics summaryStatistics = units.stream().mapToInt(unit -> unit.getAttack()).summaryStatistics(); System.out.println(summaryStatistics); // IntSummaryStatistics{count=25, sum=150, min=2, average=6,000000, max=10}
  • 74. find methods ● The find methods returns an element with the stream is not empty. But if the stream is empty, it return an Optional value.
  • 75. find methods ● The find methods returns an element with the stream is not empty. But if the stream is empty, it return an Optional value. ● findFirst() - return the “real” first element on the list Optional<Unit> firstPeon = units.stream().filter(u -> u instanceof Peon).findFirst();
  • 76. find methods ● The find methods returns an element with the stream is not empty. But if the stream is empty, it return an Optional value. ● findFirst() - return the “real” first element on the list Optional<Unit> firstPeon = units.stream().filter(u -> u instanceof Peon).findFirst(); ● findAny() - return the first element on the list Optional<Unit> anyAlive = units.parallelStream().filter(u -> u.getEnergy() > 0).findAny();
  • 77. matchs ● The match methods analyse the stream data and tell whether a predicate is valid or not
  • 78. matchs ● allMatch() - looks through ALL the data whether them match to the predicate boolean allMatch = units.stream().allMatch(unit -> unit instanceof Unit);
  • 79. matchs ● allMatch() - looks through ALL the data whether them match to the predicate boolean allMatch = units.stream().allMatch(unit -> unit instanceof Unit); ● anyMatch() - looks through the data whether any match to the predicate, if positive return the first to match and stops processing boolean anyMatch = units.stream().anyMatch(unit -> unit instanceof Healer);
  • 80. matchs ● allMatch() - looks through ALL the data whether them match to the predicate boolean allMatch = units.stream().allMatch(unit -> unit instanceof Unit); ● anyMatch() - looks through the data whether any match to the predicate, if positive return the first to match and stops processing boolean anyMatch = units.stream().anyMatch(unit -> unit instanceof Healer); ● noneMatch() - looks through ALL the data checking if none of them match to the predicate boolean noneMatch = units.stream().noneMatch(unit -> unit instanceof Hero);
  • 81. Optional ● Some operations can have an unexpected result or no result at all.
  • 82. Optional ● Some operations can have an unexpected result or no result at all. ● You could use null to those cases but it comes with more problems than solutions.
  • 83. Optional ● Some operations can have an unexpected result or no result at all. ● You could use null to those cases but it comes with more problems than solutions. ● In those case, you may also want a default value or an object that helps to determine that those cases occurred.
  • 84. Optional ● Some operations can have an unexpected result or no result at all. ● You could use null to those cases but it comes with more problems than solutions. ● In those case, you may also want a default value or an object that helps to determine that those cases occurred. ● So since Java 8, “If you want Optional, you got it!”
  • 85. Optional ● Some operations can have an unexpected result or no result at all. ● You could use null to those cases but it comes with more problems than solutions. ● In those case, you may also want a default value or an object that helps to determine that those cases occurred. ● So since Java 8, “If you want Optional, you got it!” ● And it comes in others flavors: OptionalInt, OptionalLong e OptionalDouble
  • 88. Time for a break…
  • 89. Limit, skip, distinct ● The limit() and skip() makes a Stream smaller ○ skip returns a stream without the first elements, the quantity is specified by parameter Stream<Unit> saveTheFirstThree = units.stream().skip(10);
  • 90. Limit, skip, distinct ● The limit() and skip() makes a Stream smaller ○ skip returns a stream without the first elements, the quantity is specified by parameter Stream<Unit> saveTheFirstThree = units.stream().skip(10); ○ limit returns just a stream with the first elements, the quantity is specified by parameter saveTheFirstThree.limit(5).forEach(unit -> System.out.println(unit));
  • 91. Limit, skip, distinct ● The limit() and skip() makes a Stream smaller ○ skip returns a stream without the first elements, the quantity is specified by parameter Stream<Unit> saveTheFirstThree = units.stream().skip(10); ○ limit returns just a stream with the first elements, the quantity is specified by parameter saveTheFirstThree.limit(5).forEach(unit -> System.out.println(unit)); ● The distinct method removes all the duplicates units.stream().map(unit -> unit.getClass().getSimpleName()).distinct().forEach(name -> System.out.println(name));
  • 92. Reference Method ● Let’s say that is just another way to create a lambda
  • 93. Reference Method ● Let’s say that is just another way to create a lambda ● When you want to create a lambda with just one call to a method, you could just use a reference for this method
  • 94. Reference Method ● Let’s say that is just another way to create a lambda ● When you want to create a lambda with just one call to a method, you could just use a reference for this method ● Calling a method from each instance double averageSpeed = units.stream().mapToInt(Unit::getSpeed).average().getAsDouble(); ● Receiving each instance as argument units.stream().forEach(System.out::println);
  • 95. Collectors ● Can we obtain a collection back from a stream? ● Yes, we can!
  • 96. Collectors ● Can we obtain a collection back from a stream? ● Yes, we can! ● At stream there are a method called collect() it receives a implementation for Collector, that will tell how to create the collection, and return the collection with the elements of the stream inside.
  • 97. Collectors ● Can we obtain a collection back from a stream? ● Yes, we can! ● At stream there are a method called collect() it receives a implementation for Collector, that will tell how to create the collection, and return the collection with the elements of the stream inside. ● Also, there is a Collectors class that wraps those implementations. ○ You can passa just a call for one of its methods to collect() units.stream().filter(unit -> unit.getAttack() > 0).collect(Collectors.toList());
  • 98. Grouping ● Sometimes you may want to classify the elements of a stream by some features ● For that you could make groups of them by values of the selected features ● groupingBy a feature will result in a map Map<String, List<Unit>> unitsByType = units.stream().collect(Collectors.groupingBy(unit -> unit.getClass().getSimpleName()));
  • 99. Partitioning ● groupingBy a boolean feature has a specific method partitioningBy Map<Boolean, List<Unit>> strongers = units.stream().collect(Collectors.partitioningBy(unit -> unit.getAttack() >= 10)); System.out.println(strongers.get(true)); System.out.println(strongers.get(false));
  • 100. Comparator ● Since 8th version of Java, the Comparator interface is functional. units.sort(Comparator.comparing(Unit::getAttack)); ● Beyond that some default methods were added to this interface with some commons uses. These methods can be called chaining the calls. units.sort(Comparator.comparing(Unit::getAttack).thenComparing(unit -> unit.getClass().getSimpleName()));
  • 102. What we have done? ● Reviews of Java SE ● Functional Programming ● Functional Interfaces ● Default Methods ● lambda ● Streams till exhaustion (Still have more to cover!) ● Optional ● Reference Method ● Collectors ● Comparators
  • 103. Challenge #1 ● Create an abstract class called Creator ● Creator will have a static method create that receives any Class that implements an interface Creature and return an instance of it ● The create implementation should go inside an Thread
  • 104. Challenge #2 ● Create an interface Tekpix with ○ A default method startComercial that will return a greeting message ○ An abstract method whatItDoes
  • 105. Challenge #3 plantsAndWeeds = Arrays.asList("Camellias 7", "weed 5", "Sunflower 3", "Lily 1", "weed 4", "Azalea 5", "weed 2", "Begonia 4"); ● Remove all the weeds ● Increment the number after their names by 1 ● Sort by the number at the end in decrescent order ● Print them without the numbers
  • 106. Challenge #4 ● Convert challenge #3 to stream
  • 107. Challenge #5 ● Who wants to be a millionaire? ● Figure out the statistics of Bitcoin price dataset
  • 108. Challenge #6 ● From celebrities_profile.txt ○ Find the top 10 with more followers ○ Group them by gender ○ Sort by created_at
  • 109. Bonus Challenge ● Try to solve our Java challenge at: https://bitbucket.org/dev- fitec/desafiojavafitec
  • 110. Intro to Java 8 Part 2 - More Stream - John Henrique Teixeira de Godoi jgodoi@fitec.org.br @john_godoi