HAN AdvancedJava Ch01-LambdaExpressions
HAN AdvancedJava Ch01-LambdaExpressions
Advanced Java 1
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Course Objectives
After successfully completing this course, you will be able to:
Develop object-oriented applications in Java using best coding practices
Implement classes with fields, constructors, and methods
Leverage interfaces for extensibility
Work with collections of objects
Throw and handle exceptions correctly
Employ Java best practices to create maintainable programs
Advanced Java 2
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introduction to Java Programming with Maven
CHAPTER 3: LAMBDA
EXPRESSIONS
AND FUNCTIONAL INTERFACES
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chapter Objectives
In this chapter, we will introduce:
• Default methods in interfaces
• Lambda expressions
• Method references
• Functional interfaces
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chapter Concepts
Default Methods
Lambda Expressions
Method References
Functional Interfaces
Chapter Summary
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
New Features in Java 8+
• Major new features added to Java include:
• Lambda expressions and functional interfaces
• Stream API for bulk data operations
• Time API
• Default and static methods in interfaces
• Improvements to collection API
• Improvements to concurrency API
• More…
• This course primarily focuses on Lambda expressions and
streams
• Other features are also covered such as the Date and Time library
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Java 8 and Above Changes
• As well as major changes to the language, Java 8+ has
introduced many smaller changes
• In particular, to the standard APIs
• For example, to the collection classes
• To make them easier to use
• To improve performance
• Many of the interfaces have been changed with extra methods
added
• This could have broken existing code bases that use these interfaces
• Would have made the adoption of Java 8 challenging
• Java solved this problem by providing default methods to
interfaces
• A new feature in Java 8
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Default Methods
• It is possible in Java to add concrete methods to a Java
interface
• Known as default methods
public interface Transferable {
default void transfer(Broker targetExchange){
…
}
} Indicates default
implementation
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Comparator Interface
Comparator is an example of an interface that has been
extended in Java
– Many static methods added
– Many default methods added
Provide solutions for simple tasks such as
– Sorting in reverse order
No need to write separate comparators now!
We will see these methods in use in the next few sections
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chapter Concepts
Default Methods
Lambda Expressions
Method References
Functional Interfaces
Chapter Summary
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introducing Lambda Expressions
• Anonymous classes are often used in Java
• More compact syntax than defining an explicit class used just once
• Consider the following simple example:
class SimpleRunnable implements Runnable{
@Override
public void run() {
System.out.println("Running Thread");
}
}
thread.start();
}
}
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introducing Lambda Expressions (continued)
• The example can be reworked using an anonymous class
public class ThreadDemo {
public static void main(String[] args) {
new Thread(new Runnable(){
@Override
public void run() {
System.out.println("Running Anonymous Thread");
}
}).start();
}
}
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Lambda Expression Solution
• Lambdas can be used to provide a neater solution
• For example, reworking thread example on the previous
slide results in the following code
Lambda expression
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introducing Lambda Expressions
• Lambda expressions are a simplification of anonymous
classes
• When implementing an interface with one abstract method
• Can be considered as an anonymous method
• More compact syntax than traditional Java method
• No name, modifiers, or return type
• In some cases, no parameter type(s)
• Use case
• Where a method will only be used once
• Can be passed as parameters to other methods
• General syntax is:
• (Parameter List) -> Body of method
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Another Lambda Expression
Example
Consider sorting the following list of strings
List<String> currencies =
Arrays.asList("USD", "JPY", "EUR", "HKD", "INR", "AUD");
Lambda expression
This can be further simplified to:
Collections.sort(currencies, (a,b)-> a.compareTo(b));
Lambda expression
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Internal Iteration
• Consider printing the elements of the following collection to
the console
List<String> currencies =
Arrays.asList("USD", "JPY", "EUR", "HKD", "INR", "AUD");
• We have to do two things:
1. Write a loop to iterate over the collection
2. Print each element to the console
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Internal Iteration (continued)
• Every time we want to iterate over a collection, we have to
write the loop
• Lots of repetitive code
• Usually only the work we want to do on the elements that changes
• Java 8 has modified the Java 8 Iterable interface
• Added new method forEach
• Allows collections to provide iteration internally
• User just supplies work to be done on each element
(currency) ->
System.out.printf("Currency is %s%d", currency)
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Exercise 1.1: Working with Lambda Expressions
Write the following methods that return a lambda
expression performing a specified action:
• PerformOperation isOdd(): The lambda expression must
return true if a number is odd or false if it is even.
• PerformOperation isPrime(): The lambda expression must
return true if a number is prime or false if it is composite.
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chapter Concepts
Default Methods
Lambda Expressions
Method References
Functional Interfaces
Chapter Summary
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Domain Classes
• To further explain Java 8 features, we will use the following
classespublic abstract class Order {
private Currency currency;
private double amount;
private Side side;
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Domain Classes (continued)
public class MarketOrder extends Order {
@Override
public boolean match(Order order) {
…
}
public MarketOrder(Currency currency, double amount, Side side) {
super(currency, amount, side);
}
}
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introducing Method References
• Lambda expressions are an implementation of the single
abstract method in a functional interface
• Often, the expression simply calls a concrete method in an
existing class
• Consider the example below
– The Lambda expression just calls the println method
Currencies.forEach(c-> System.out.println(c));
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Method References
• Method references allow reuse of existing method definitions
• They can be passed just like Lambda expressions
• Consider sorting a collection of orders by price
• Using the Comparators comparing() method, we can write:
List<Order> orders = …
Collections.sort(orders, comparing(Order::getAmount));
Default Methods
Lambda Expressions
Method References
Functional Interfaces
Chapter Summary
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Functional Interfaces
• Many interfaces in Java have just one abstract method
• Known as functional interfaces
• For example, Runnable, Comparator
• Results in a class being written to contain the method
• Can use a Lambda expression instead
• A Lambda expression can be supplied wherever an
implementation of a functional interface is required
• The Lambda expression will be matched to the abstract method
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Defining Functional Interfaces
• It is possible to explicitly define a functional interface
• Compiler will check that interface meets functional interface
requirements
• Use @FunctionalInterface to explicitly define functional
interface Compiler enforces functional
interface requirements
• Annotation is optional
@FunctionalInterface
public interface Transferable{
void transfer(Broker targetExchange);
}
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Built-In Functional Interfaces
• Java 8 has many built-in functional interfaces
– In the package java.util.function
• Often used with enhancements to collection classes
– Make filtering and processing of data simpler
• We will examine some of these functional interfaces now,
including:
– Predicate
– Consumer
– Function
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introducing Predicates
• Consider the following collection of orders
• The collection contains a mixture of BUY and SELL side orders
List<Order> orders = …
• Let's assume we want to print out all the BUY side orders
for(Order order : orders){
if(order.getSide() == BUY){
System.out.println(order);
}
}
• Now consider printing all the SELL side orders
for(Order order : orders){
if(order.getSide() == SELL){
System.out.println(order);
}
}
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Introducing Predicates (continued)
• There is a lot of duplication in the previous slide
• The Predicate interface can help us reduce this
• Predicate interface defines one method
• It is a functional interface
• Usually implemented using a Lambda expression
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Using Predicate
• To prevent duplication of previous code, can use Lambdas
• Write a method that receives a predicate
• Method will print any item in the list that matches the predicate
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
The Consumer Functional Interface
• This interface is used when an operation is to be performed
on a single input argument
public interface Consumer<T>{
void accept(T t);
}
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Consumer Example
• The following code will call accept on any supplied Consumer
static void evaluate(List<Order> orders ,
Consumer<Order> consumer){
for(Order order : orders) {
consumer.accept(order);
}
}
Apply consumers
• Here, we just supply two different consumers
evaluate(orders, o -> System.out.println(o.getAmount()));
evaluate(orders, o -> System.out.println(o.getCurrency()));
Supply consumers
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Further Simplifying the Consumer Example
• The Iterable interface has been enhanced with a forEach
method
• Signature of the method is:
void forEach(Consumer<? super T> action)
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Function Example
• The following example shows a simple function defined to
calculate the average value of the orders
Receives List<Order>
and returns Double
Invoke function
System.out.println(averageOrder.apply(orders));
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Composing Functions
• The function interface has default methods that return a
Function
– Allows functions to be chained
To create processing/transformation pipelines
• Function andThen(Function after)
– The after function is applied after the calling function
• Function compose(Function before)
– The before function is applied first and then the calling function
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Composing Function Example
• The following shows the use of compose and andThen
Function<Integer,Integer> addOne = x -> x+1;
Function<Integer,Integer> multiplyByTwo = x -> x*2;
Function<Integer,Integer> andThenExample =
addOne.andThen(multiplyByTwo);
Function<Integer,Integer> composeExample =
addOne.compose(multiplyByTwo);
System.out.println(andThenExample.apply(10));
System.out.println(composeExample.apply(10));
List<Order> orders = …
Collections.sort(orders,
comparing(Order::getAmount).reversed());
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chaining Comparators
• Assume we sort orders by amount, but we get two orders of
the same amount?
• In this case, we want the orders to be further sorted by side (SELL
or BUY)
• The comparator provides a default method
thenComparing() that allows chaining
List<Order> orders = …
Collections.sort(orders,
comparing(Order::getAmount).
thenComparing(Order::getSide));
Chain comparator
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Further Functional Interfaces
• There are a number of other functional interfaces available
• UnaryOperator<T>
• BinaryOperator<T>
• Supplier<T>
• Many more
• We will see some more later in the course
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Exercise 1.2: Working with Functional Interfaces
Create a calculator to perform:
1) Arithmetic operation 2) Scientific operation 3) Trigonometric operation with individual operations separately or combined with binary operation
or multiple operation at a stretch (which is mutation state). A console input has to be taken until return key is pressed. Once the return key is
pressed the equation has to be evaluated with error handling.
Evaluate the equation from left to right (no priority to be taken at this stage)
Hint: Step 1: create new java project 2.
Step 2: create functional interface Arithmetic.
Step 3: create Enum ScintificOp which has constant abs, sqrt
Step 4: create Enum TrignometircOp which has constants sin, tan, cos, sec.
Step 5: create the class Add, Sub, Mul, Div and Percent which over rides the method of Arithmetic.
Step 6: create Expression_evaluator Class to evaluate Airthmetic, trigonometric and scientific operation it should evaluate the expression of
kind "10 + sqrt(4) + sin(90)". ( of any combination and any length from left to right).
Step 7: Add Date evaluator class to evaluate date as below using functional programming .
Add (date, integer ) : number of day is added to date to give new date
Add (date, date): two dates are to give new date
Sub(date, integer) number of days are subtracted from existing date to give new date
Sub(date, date) two date are subtracted to give number of day in difference(integer value as output)
Step 8 Now you should have Date_Evaluator class to evaluate the date and Expression_Evaluator to evaluate Arithmetic expressions,
scientific expression and trigonometric expression.
Step 9: create main class to evaluate the expression given.
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chapter Concepts
Default Methods
Lambda Expressions
Method References
Functional Interfaces
Chapter Summary
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Chapter Summary
In this chapter, we have introduced:
• Default methods in interfaces
• Lambda expressions
• Method references
• Functional interfaces
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.