0% found this document useful (0 votes)
6 views

HAN AdvancedJava Ch01-LambdaExpressions

Uploaded by

hitha.ps1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

HAN AdvancedJava Ch01-LambdaExpressions

Uploaded by

hitha.ps1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Welcome!

Advanced Java Introduction

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

• Interfaces can also have static methods defined in Java 8+

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");
}
}

public class ThreadDemo {


public static void main(String[] args) {
Thread thread = new Thread(new SimpleRunnable());

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

public class ThreadDemo {


public static void main(String[] args) {
new Thread(()->System.out.println(”Lambda Thread")).start();
}
}

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");

Using a Lambda expression, we can write:


Collections.sort(currencies,
(String a, String b) -> { return a.compareTo(b);});

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

for(String currency: currencies){


System.out.println(currency);
}

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

• Loop on previous slide can be rewritten as:


currencies.forEach(c-> System.out.println(c));

• This feature is known as internal iteration


Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Lambda Expression Syntax
• A Lambda expression consists of:
1. A parameter list
2. Followed by an arrow ->
3. Followed by a function body
• A zero argument Lambda expression example:
• () -> System.out.println("Lambda")
• A one argument Lambda expression example:
• (String currency) ->
System.out.printf("Currency is %s%d", currency)
• A Lambda expression with more than one argument:
• (String fromCurrency, String toCurrency) ->
System.out.printf("Converting from %s to %s %n",
fromCurrency,toCurrency)
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Lambda Expression Syntax
(continued)
• The type of parameters can be omitted if the type can be inferred
by the compiler
No type specified

(currency) ->
System.out.printf("Currency is %s%d", currency)

• The parenthesis on a parameter list are optional if there is only one


parameter
No parenthesis

currency -> System.out.printf("Currency is %s%d", currency)

• If a Lambda expression has a return value, no type needs to be


specified
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Multiple Line Lambda Expressions
• A Lambda expression may have more than one statement
• Statements must be enclosed in a block {}
public class ThreadDemo {
public static void main(String[] args) {
new Thread(()-> {
System.out.println(”Lambda Thread Line One")
System.out.println(”Lambda Thread Line Two")
}).start();
}
}

Multiple line Lambda


expression requires {}

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;

public Order(Currency currency, double amount, Side side) {


this.currency = currency; this.amount = amount; this.side = side;
}
public abstract boolean match(Order order);

public Currency getCurrency() {


return currency;
}
public double getAmount() {
return amount;
}
public Side getSide() {
return 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);
}
}

public class LimitOrder extends Order {


private double limit;

public LimitOrder(Currency currency, double amount, Side side, double limit) {


super(currency, amount, side);
this.limit = limit;
}
@Override
public boolean match(Order order) {

}
}

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));

• Using a method reference, the code can be further simplified


– println will be passed the current value in the collection on each
iteration
currencies.forEach(System.out::println); Method reference

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));

Generates Comparator Method reference

• Comparing() will generate a Comparator using the value returned by method


whose reference is supplied
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Types of Method References
• There are four types of method references
• Static
• Bound instance
• Unbound instance
• Constructor
• Static references are created using
ClassName::staticMethodName
• Bound instance references are created using
objectReference::methodName
• Unbound instance references are created using
ClassName:methodName
• Constructor references are created using ClassName::new
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.
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

public interface Predicate<T>{


boolean test(T t);
}

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

static void evaluate(List<Order> orders ,


Predicate<Order> predicate){
for(Order order : orders){
if(predicate.test(order)){ Apply predicate
System.out.println(order);
}
}
}
Supply predicates

evaluate(orders, o -> o.getSide()==BUY);


evaluate(orders, o -> o.getSide() ==SELL);

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);
}

• Enables general methods to be written that apply work to


collections
• Such as:
• Persisting items in collection
• Printing items

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)

• And the default implementation behaves as:


for (T t : this)
action.accept(t);
• The example on the previous slide can be simplified to:
static void evaluate(List<Order> orders ,
Consumer<Order> consumer){
orders.forEach(consumer);
} Apply consumer
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
The Function Functional Interface
• Represents a unary function
• Performs a function on a single argument of type T
• Returns a result of type R

public interface Function<T,R>{


R apply(T t);
}

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

Function<List<Order>, Double> averageOrder = x -> {


double total = 0.0;
for(Order order: x) {
total+= order.getAmount();
}
return total/x.size();
};

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));

Apply processing chain


• What two values are output to the console when this code
runs?
Advanced Java
© 2021 Copyright TechEd Trainings, LLP. All rights reserved. Not to be reproduced without prior written consent.
Composing Comparators
• Earlier, we sorted orders by amount with the following code
List<Order> orders = …
Collections.sort(orders, comparing(Order::getAmount));

Generates Comparator Method reference

• What if we wanted to sort the orders in decreasing amount?


• The Comparator interface provides a default method reversed()
Reverses sort order

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.

You might also like