SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Functional Programming in Java 8
Omar Bashir
Interfaces
Default Methods
● Methods implemented in interfaces that are
available to all their implementations.
– Removes the need to provide a common implementation
either in every class implementing the interface or in a
common base class implementation.
– Makes existing interface implementations future-proof.
● Interface implementations can override default
implementations.
● Non-final methods in the Object base class cannot
be overridden by default methods.
Default Methods (Example)
● An instrumentation interface for vehicles.
– Methods
● Return trip distance.
● Return trip time.
● Default method to return average speed by dividing the trip
distance by the trip time.
● Implementations
– Aircraft instrumentation to which leg distances with
corresponding times are added.
– Car instrumentation to which distance travelled in hourly
intervals is added.
– Statue instrumentation that returns 0 for all methods.
Instrumentation Interface
public interface Instrumentation {
double getTripDistance();
double getTripTime();
default double getAverageSpeed() {
return getTripDistance()/getTripTime();
}
}
CarInstrumentation
public class CarInstrumentation implements Instrumentation {
private final List<Double> samples;
public CarInstrumentation() {
samples = new ArrayList<>();
}
public void addSample(double distance) {
samples.add(distance);
}
@Override
public double getTripDistance() {
double sum = 0.0;
for(double value : samples) {
sum += value;
}
return sum;
}
@Override
public double getTripTime() {
return samples.size();
}
}
AircraftInstrumentation
public class AircraftInstrumentation implements Instrumentation {
private final List<Double> legTimes;
private final List<Double> legDistances;
public AircraftInstrumentation() {
legTimes = new ArrayList<>();
legDistances = new ArrayList<>();
}
public void addLeg(double legDistance, double legTime) {
legTimes.add(legTime);
legDistances.add(legDistance);
}
private double add(List<Double> data) {
double sum = 0.0;
for(double value : data) {
sum += value;
}
return sum;
}
@Override
public double getTripDistance() {
return add(legDistances);
}
@Override
public double getTripTime() {
return add(legTimes);
}
}
Statue Interface
public class StatueInstrumentation implements Instrumentation {
@Override
public double getTripDistance() {
return 0;
}
@Override
public double getTripTime() {
return 0;
}
@Override
public double getAverageSpeed() {
return 0;
}
}
Example
public static void main(String[] args) {
System.out.printf("Statue speed = %.2fn", new
StatueInstrumentation().getAverageSpeed());
CarInstrumentation carInst = new CarInstrumentation();
carInst.addSample(50);
carInst.addSample(70);
carInst.addSample(60);
System.out.printf("Car speed = %.2fn", carInst.getAverageSpeed());
AircraftInstrumentation planeInst = new AircraftInstrumentation();
planeInst.addLeg(70, 1.5);
planeInst.addLeg(25, 0.25);
planeInst.addLeg(75, 1.25);
planeInst.addLeg(110, 1);
System.out.printf("Plane speed = %.2fn", planeInst.getAverageSpeed());
}
Default Methods
● With great power comes great responsibility.
– Developers may be tempted to extend existing
implementations using default methods.
● This may require overriding default methods in some interface
implementation to accommodate specifics of implementations.
– Ideally, default methods should
● contain common functionality across interface
implementations.
● contain functionality that can be defined in terms of the
abstract methods.
– If overriding default methods becomes common, these
may be converted to abstract methods.
Static Methods
● Similar to static methods in classes.
● Allows methods to be called without implementing an
interface.
● Allows grouping of relevant utility methods with the
corresponding interfaces.
– No need to write utility companion classes., e.g.,
● Static methods are not part of the implementing
classes.
● To invoke, prefix the static method name with the
name of the interface.
● Static methods can be invoked from default methods.
StaticMethods(Example)
public interface Calculator {
static double add(double a, double b) {
return a + b;
}
static double subtract(double a, double b) {
return a - b;
}
static double multiply(double a, double b) {
return a * b;
}
static double divide(double a, double b) {
return a / b;
}
}
public static void main(String[] args) {
double a = 5.0;
double b = 2.5;
System.out.println(Calculator.add(a, b));
System.out.println(Calculator.subtract(a, b));
System.out.println(Calculator.multiply(a, b));
System.out.println(Calculator.divide(a, b));
}
Usage
Lambda Expressions
Anonymous Function Calls
● Syntax
– parameter ­> expression
– Translates to
● function(parameter) where function implementation
contains the expression
– Parameter syntax,
● Parenthesis optional only for single parameters in function call.
● Parameter types are optional.
– Expression syntax
● Braces and return required for multi-line expressions.
● Expressions can be method references.
Functional Interfaces
● Specifying type of lambda expressions.
– To assign lambda expressions to variables and used
repeated.
– To declare lambda expressions as function parameters.
● Standard Java interfaces with following exceptions,
– Only one abstract method in the interface.
● SAM (Single Abstract Method) interfaces.
– Can be decorated with annotation
@FunctionalInterface for compiler to check that
interface is SAM interface.
● Functional interfaces for common use cases already
specified in java.util.function package.
– Custom functional interfaces rarely required.
Lambda Expression - Example
// BiFunction takes two arguments and returns the result.
// The following statement effectively creates an anonymous
// class implementing BiFunction where the apply method adds the
// two arguments and returns the result.
BiFunction<Integer, Integer, Integer> intAdder = (a, b) -> a + b;
int op1 = 5;
int op2 = 25;
int sum = intAdder.apply(op1, op2);
System.out.printf("%d + %d = %dn", op1, op2, sum);
Lambda Expression - Example
public static void main(String[] args) {
int op1 = 25;
int op2 = 5;
int sum = process(op1, op2, (a, b) -> a + b);
int diff = process(op1, op2, (a, b) -> a - b);
int product = process(op1, op2, (a, b) -> a * b);
int div = process(op1, op2, (a, b) -> a / b);
System.out.printf("%d + %d = %dn", op1, op2, sum);
System.out.printf("%d - %d = %dn", op1, op2, diff);
System.out.printf("%d * %d = %dn", op1, op2, product);
System.out.printf("%d / %d = %dn", op1, op2, div);
}
private static int process(
int x,
int y,
BiFunction<Integer, Integer, Integer> processor) {
return processor.apply(x, y);
}
Lambda Expression - Example
public class FunctionalCalculator {
public static void main(String[] args) {
if (args.length == 3) {
Map<String, BiFunction<Double, Double, Double>> calculator = new HashMap<>();
calculator.put("+", (a, b) -> a + b);
calculator.put("-", (a, b) -> a - b);
calculator.put("*", (a, b) -> a * b);
calculator.put("/", (a, b) -> a / b);
String operator = args[1];
if (calculator.containsKey(operator)) {
Double operand1 = Double.parseDouble(args[0]);
Double operand2 = Double.parseDouble(args[2]);
double result = calculator.get(operator).apply(operand1, operand2);
System.out.printf("%.2f %s %.2f = %.2f", operand1, operator, operand2, result);
} else {
System.out.printf("Operator %s not recognisedn", operator);
System.out.println("Operators:: +, -, *, /");
}
} else {
System.out.println("USAGE:: Command line arguments operand1 operator operand2");
System.out.println("Operators:: +, -, *, /");
}
}
}
Closure
● Lambda expressions allow capturing variables and
methods defined in their scope.
– Lambda expressions close over the scope in which they
exist.
● The state of the variables captured stay with the
expressions even if they are passed to other
methods and executed there.
● Captured variables are effectively final, i.e.,
– Mutating these values results in a compilation error.
Closure-Example
public class WeightCalculator {
final double mass;
public WeightCalculator(double mass) {
this.mass = mass;
}
public Function<Double, Double> getCalculator() {
return g -> this.getWeight(mass, g);
}
private double getWeight(double m, double g) {
return m * g;
}
}
public static void main(String[] args) {
double mass = 10;
Function<Double, Double> calculator =
new WeightCalculator(mass).getCalculator();
double weightOnEarth = calculator.apply(9.8);
double weightOnMars = calculator.apply(3.77);
System.out.printf("%.2f kg on Earth is %.2f N on Earthn",
mass, weightOnEarth);
System.out.printf("%.2f kg on Earth is %.2f N on Marsn",
mass, weightOnMars);
}
Method Referencing
● Obtaining the reference of a method so that
– It can be assigned to a matching functional interface
variable,
– And that functional interface can be executed later.
● :: is the referencing operator.
● Applies to,
– Static methods, e.g., ClassName::staticMethodName.
– Instance methods, e.g.,
ObjectRef::instanceMethodName.
– Constructors, e.g., ClassName::new.
MethodReferencing-
Example
public class Doubler {
public static double doubleIt(double value) {
return 2 * value;
}
}
public static void main(String[] args) {
Function<Double, Double> doubler = Doubler::doubleIt;
Consumer<String> printer = System.out::println;
Function<Double, Double> maker = Double::new;
workIt(doubler, printer, maker, 3);
}
private static void workIt(
Function<Double, Double> worker,
Consumer<String> consumer,
Function<Double, Double> creater,
double value) {
double result = worker.apply(value);
consumer.accept(creater.apply(result).toString());
}
Optional
Optional
● Container class that may or may not contain a non-
null value.
● Contains methods that
– determine presence or absence of value.
– perform operations based on presence or absence of a
value.
– operate on the contained value.
● Protects against NullPointerException.
Key Members
● Construction using static factory methods,
– empty()
● returns an empty Optional instance.
– of(T value) 
● returns an Optional instance with value.
– ofNullable(T value)
● returns an Optional instance with the supplied value if non-
nullable, an empty instance otherwise.
Key Members
● Accessors,
– get() 
● returns contained value or throws NoSuchElementException if
empty.
– isPresent()
● returns true if not empty.
– orElse(T other) 
● returns enclosed value if not empty otherwise returns other.
– orElseGet(Supplier<? extends T> other)
● returns enclosed value if not empty otherwise calls other to get
a value.
Key Members
● Transformation, consumer and filter,
– ifPresent(Consumer<? super T> consumer) 
● calls consumer on value if present otherwise does nothing.
– filter(Predicate<? super T> predicate) 
● returns this Optional if the value is present and predicate returns
true otherwise returns empty Optional.
– map(Function<? super T, ? extends U> mapper) 
● transforms the value using the mapper if present otherwise does
nothing.
– flatMap(Function<? super T, Optional<U>> 
mapper)
● applies mapper to value and returns an Optional bearing
transformed value.
Optional-Example
/**
* Find at matching name from the list and if present. print the value
* after converting it into uppercase.
* @param args
*/
public static void main(String[] args) {
List<String> names = Arrays.asList("George Patton", "Omar Bradley",
"Bernard Montgomery", "Erwin Romel");
Optional<String> name = find(names, "Brad");
name.map(x -> x.toUpperCase()).ifPresent(x -> System.out.println(x));
System.out.println("DONE");
}
private static Optional<String> find(List<String> names, String value) {
Optional<String> result = Optional.empty();
boolean found = false;
Iterator<String> itr = names.iterator();
while (!found && itr.hasNext()) {
String item = itr.next();
if (item.contains(value)) {
found = true;
result = Optional.of(item);
}
}
return result;
}
Streams
Streams
● An abstraction allowing generic and declarative
processing of collections.
● Operations on streams are
– Intermediate operations
● Return a stream object representing intermediate results.
● Allow chaining of operations.
– Terminal operations
● Either perform a void operation or return a non-stream result.
● Immutable operations
– Original data source is not modified.
Streams
● Obtaining a stream on a collection,
– stream() to return a sequential stream.
– parallelStream() to create a stream capable of
executing in multiple threads.
● Streams evaluated lazily,
– Once a terminal operation is executed.
● Streams cannot be reused,
– Once a terminal operation executed, the stream is closed.
– Call get() on the stream before calling a terminal
operation to get a copy of the stream.
Streams - Example
public class Finder {
/**
* Find at matching name from the list and if present. print the
* value after converting it into uppercase.
* @param args
*/
public static void main(String[] args) {
List<String> names = Arrays.asList("George Patton",
"Omar Bradley", "Bernard Montgomery", "Erwin Romel");
Optional<String> name = names.stream().
filter(x -> x.contains("Bernard")).findFirst();
name.map(x -> x.toUpperCase()).
ifPresent(x -> System.out.println(x));
System.out.println("Done");
}
}
Collectors
● Implementation of the Collector interface.
● Performs useful reduction operations on stream,
e.g.,
– Accumulation of elements into collections,
– Summarising values,
– Grouping,
– Partitioning
● Typically used in the collect method of the stream to
return the final collection after the stream pipeline
has executed.
Collectors - Example
/**
* Return a list of even numbers from a list of string
* representation of integers.
* @param args
*/
List<String> numStr = Arrays.asList("53", "26", "33", "77",
"2", "8", "9", "98");
List<Integer> evenNums = numStr.stream().
map(x -> Integer.parseInt(x)).
filter(x -> x % 2 == 0).
collect(Collectors.toList());
evenNums.forEach(System.out::println);
Stream Reduction - Example
List<Double> nums = Arrays.asList(25.5, 23.25, 17.0, 9.25);
/*
* reduce takes an initial accumulator value and a BiFunction
* extension that takes the accumulated value, iteratively adds
* the elements in the stream.
*/
double average = nums.stream().
reduce(0.0, (acc, x) -> acc + x)/nums.size();
System.out.printf("Average = %.3f", average);
Collector Reduction - Example
List<Double> nums = Arrays.asList(25.5, 23.25, 17.0, 9.25);
double average = nums.stream().
collect(Collectors.averagingDouble(x -> x));
System.out.printf("Average = %.3f", average);
Creating Streams
● static Stream<T> of(T... values)
– Creates a stream of values specified.
● static  IntStream range(int inclusiveStart, 
int exclusiveEnd)
– Sequentially ordered stream of integers with increment of
1 excluding the end value.
● static IntStream rangeClosed(int 
inclusiveStart, int inclusiveEnd)
– Sequentially ordered stream of integers with increment of
1 including the end value.
IntStream - Example
IntStream range = IntStream.rangeClosed(1, num);
int factorial = range.reduce(1, (acc, x) -> acc * x);
System.out.printf("%d! = %dn", num, factorial);
flatMap
flatMap
● Consider a collection of collections of items.
– flatMap used to transform items of inner collections.
– and then flatten the collection of collections of
transformed items to a collection of transformed
items.
● Defined for
– Stream,
– Optional
Example – Stream flatMap
List<List<String>> linesOfWords =
Arrays.asList(Arrays.asList("Incy", "wincy", "spider"),
Arrays.asList("Climbing", "up", "the", "spout"));
Stream<String> dataStream = linesOfWords.stream().
flatMap(line -> line.stream().map(word -> word.toUpperCase()));
List<String> data = dataStream.collect(Collectors.toList());
data.forEach(System.out::println);
INCY
WINCY
SPIDER
CLIMBING
UP
THE
SPOUT
Example – Flattening Optional
Collections
List<Optional<Integer>> nums = Arrays.asList(Optional.of(3),
Optional.of(5),
Optional.empty(),
Optional.of(9));
System.out.println(nums);
List<Integer> filteredNums = nums.stream().
filter(n -> n.isPresent()).
map(n -> n.get()).
collect(Collectors.toList());
System.out.println(filteredNums);
[Optional[3],
Optional[5],
Optional.
empty,
Optional[9]]
[3, 5, 9]

Weitere ähnliche Inhalte

Was ist angesagt?

Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr
Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr
Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr AgileNCR2013
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functionsSwapnil Yadav
 
What's new in Scala 2.13?
What's new in Scala 2.13?What's new in Scala 2.13?
What's new in Scala 2.13?Hermann Hueck
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppteShikshak
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in CHarendra Singh
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2Shameer Ahmed Koya
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptWill Livengood
 
EST 102 Programming in C-MODULE 4
EST 102 Programming in C-MODULE 4EST 102 Programming in C-MODULE 4
EST 102 Programming in C-MODULE 4NIMMYRAJU
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and typesmubashir farooq
 

Was ist angesagt? (20)

Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr
Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr
Agile NCR 2013- Anirudh Bhatnagar - Hadoop unit testing agile ncr
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
Function in c
Function in cFunction in c
Function in c
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
What's new in Scala 2.13?
What's new in Scala 2.13?What's new in Scala 2.13?
What's new in Scala 2.13?
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
 
Function in C
Function in CFunction in C
Function in C
 
C functions
C functionsC functions
C functions
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2User Defined Functions in MATLAB part 2
User Defined Functions in MATLAB part 2
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
R: Apply Functions
R: Apply FunctionsR: Apply Functions
R: Apply Functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
EST 102 Programming in C-MODULE 4
EST 102 Programming in C-MODULE 4EST 102 Programming in C-MODULE 4
EST 102 Programming in C-MODULE 4
 
Function C++
Function C++ Function C++
Function C++
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
functions in C and types
functions in C and typesfunctions in C and types
functions in C and types
 

Andere mochten auch

Coding for 11 Year Olds
Coding for 11 Year OldsCoding for 11 Year Olds
Coding for 11 Year OldsOmar Bashir
 
SOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter SystemeSOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter SystemeMario Rodler
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID PrinciplesGanesh Samarthyam
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsHayim Makabee
 

Andere mochten auch (8)

Coding for 11 Year Olds
Coding for 11 Year OldsCoding for 11 Year Olds
Coding for 11 Year Olds
 
SOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter SystemeSOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter Systeme
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 
Solid principles
Solid principlesSolid principles
Solid principles
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
 
The SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design PatternsThe SOLID Principles Illustrated by Design Patterns
The SOLID Principles Illustrated by Design Patterns
 

Ähnlich wie Functional Programming in Java 8

documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxBruceLee275640
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Jason Lotito
 

Ähnlich wie Functional Programming in Java 8 (20)

Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
functions
functionsfunctions
functions
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Java 8
Java 8Java 8
Java 8
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13Load Testing with PHP and RedLine13
Load Testing with PHP and RedLine13
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 

Mehr von Omar Bashir

Cloud migration challenges london ct os
Cloud migration challenges   london ct osCloud migration challenges   london ct os
Cloud migration challenges london ct osOmar Bashir
 
5 Software Development Lessons From a Mountaineer
5 Software Development Lessons From a Mountaineer5 Software Development Lessons From a Mountaineer
5 Software Development Lessons From a MountaineerOmar Bashir
 
Technology Agility
Technology AgilityTechnology Agility
Technology AgilityOmar Bashir
 
Quality Loopback
Quality LoopbackQuality Loopback
Quality LoopbackOmar Bashir
 
Achieving Technological Agility
Achieving Technological AgilityAchieving Technological Agility
Achieving Technological AgilityOmar Bashir
 
Technical Debt: Measured and Implied
Technical Debt: Measured and ImpliedTechnical Debt: Measured and Implied
Technical Debt: Measured and ImpliedOmar Bashir
 
Distilling Agile for Effective Execution
Distilling Agile for Effective ExecutionDistilling Agile for Effective Execution
Distilling Agile for Effective ExecutionOmar Bashir
 
Authorisation: Concepts and Implementation
Authorisation: Concepts and ImplementationAuthorisation: Concepts and Implementation
Authorisation: Concepts and ImplementationOmar Bashir
 
High Speed Networks - Applications in Finance
High Speed Networks - Applications in FinanceHigh Speed Networks - Applications in Finance
High Speed Networks - Applications in FinanceOmar Bashir
 
Computing at Schools: A Guide to Parents
Computing at Schools: A Guide to ParentsComputing at Schools: A Guide to Parents
Computing at Schools: A Guide to ParentsOmar Bashir
 
Information technology
Information technologyInformation technology
Information technologyOmar Bashir
 
Maths with Programming
Maths with ProgrammingMaths with Programming
Maths with ProgrammingOmar Bashir
 
Code Club Talk 2014
Code Club Talk 2014Code Club Talk 2014
Code Club Talk 2014Omar Bashir
 

Mehr von Omar Bashir (14)

Cloud migration challenges london ct os
Cloud migration challenges   london ct osCloud migration challenges   london ct os
Cloud migration challenges london ct os
 
5 Software Development Lessons From a Mountaineer
5 Software Development Lessons From a Mountaineer5 Software Development Lessons From a Mountaineer
5 Software Development Lessons From a Mountaineer
 
Why Java ?
Why Java ?Why Java ?
Why Java ?
 
Technology Agility
Technology AgilityTechnology Agility
Technology Agility
 
Quality Loopback
Quality LoopbackQuality Loopback
Quality Loopback
 
Achieving Technological Agility
Achieving Technological AgilityAchieving Technological Agility
Achieving Technological Agility
 
Technical Debt: Measured and Implied
Technical Debt: Measured and ImpliedTechnical Debt: Measured and Implied
Technical Debt: Measured and Implied
 
Distilling Agile for Effective Execution
Distilling Agile for Effective ExecutionDistilling Agile for Effective Execution
Distilling Agile for Effective Execution
 
Authorisation: Concepts and Implementation
Authorisation: Concepts and ImplementationAuthorisation: Concepts and Implementation
Authorisation: Concepts and Implementation
 
High Speed Networks - Applications in Finance
High Speed Networks - Applications in FinanceHigh Speed Networks - Applications in Finance
High Speed Networks - Applications in Finance
 
Computing at Schools: A Guide to Parents
Computing at Schools: A Guide to ParentsComputing at Schools: A Guide to Parents
Computing at Schools: A Guide to Parents
 
Information technology
Information technologyInformation technology
Information technology
 
Maths with Programming
Maths with ProgrammingMaths with Programming
Maths with Programming
 
Code Club Talk 2014
Code Club Talk 2014Code Club Talk 2014
Code Club Talk 2014
 

Kürzlich hochgeladen

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Functional Programming in Java 8

  • 1. Functional Programming in Java 8 Omar Bashir
  • 3. Default Methods ● Methods implemented in interfaces that are available to all their implementations. – Removes the need to provide a common implementation either in every class implementing the interface or in a common base class implementation. – Makes existing interface implementations future-proof. ● Interface implementations can override default implementations. ● Non-final methods in the Object base class cannot be overridden by default methods.
  • 4. Default Methods (Example) ● An instrumentation interface for vehicles. – Methods ● Return trip distance. ● Return trip time. ● Default method to return average speed by dividing the trip distance by the trip time. ● Implementations – Aircraft instrumentation to which leg distances with corresponding times are added. – Car instrumentation to which distance travelled in hourly intervals is added. – Statue instrumentation that returns 0 for all methods.
  • 5. Instrumentation Interface public interface Instrumentation { double getTripDistance(); double getTripTime(); default double getAverageSpeed() { return getTripDistance()/getTripTime(); } }
  • 6. CarInstrumentation public class CarInstrumentation implements Instrumentation { private final List<Double> samples; public CarInstrumentation() { samples = new ArrayList<>(); } public void addSample(double distance) { samples.add(distance); } @Override public double getTripDistance() { double sum = 0.0; for(double value : samples) { sum += value; } return sum; } @Override public double getTripTime() { return samples.size(); } }
  • 7. AircraftInstrumentation public class AircraftInstrumentation implements Instrumentation { private final List<Double> legTimes; private final List<Double> legDistances; public AircraftInstrumentation() { legTimes = new ArrayList<>(); legDistances = new ArrayList<>(); } public void addLeg(double legDistance, double legTime) { legTimes.add(legTime); legDistances.add(legDistance); } private double add(List<Double> data) { double sum = 0.0; for(double value : data) { sum += value; } return sum; } @Override public double getTripDistance() { return add(legDistances); } @Override public double getTripTime() { return add(legTimes); } }
  • 8. Statue Interface public class StatueInstrumentation implements Instrumentation { @Override public double getTripDistance() { return 0; } @Override public double getTripTime() { return 0; } @Override public double getAverageSpeed() { return 0; } }
  • 9. Example public static void main(String[] args) { System.out.printf("Statue speed = %.2fn", new StatueInstrumentation().getAverageSpeed()); CarInstrumentation carInst = new CarInstrumentation(); carInst.addSample(50); carInst.addSample(70); carInst.addSample(60); System.out.printf("Car speed = %.2fn", carInst.getAverageSpeed()); AircraftInstrumentation planeInst = new AircraftInstrumentation(); planeInst.addLeg(70, 1.5); planeInst.addLeg(25, 0.25); planeInst.addLeg(75, 1.25); planeInst.addLeg(110, 1); System.out.printf("Plane speed = %.2fn", planeInst.getAverageSpeed()); }
  • 10. Default Methods ● With great power comes great responsibility. – Developers may be tempted to extend existing implementations using default methods. ● This may require overriding default methods in some interface implementation to accommodate specifics of implementations. – Ideally, default methods should ● contain common functionality across interface implementations. ● contain functionality that can be defined in terms of the abstract methods. – If overriding default methods becomes common, these may be converted to abstract methods.
  • 11. Static Methods ● Similar to static methods in classes. ● Allows methods to be called without implementing an interface. ● Allows grouping of relevant utility methods with the corresponding interfaces. – No need to write utility companion classes., e.g., ● Static methods are not part of the implementing classes. ● To invoke, prefix the static method name with the name of the interface. ● Static methods can be invoked from default methods.
  • 12. StaticMethods(Example) public interface Calculator { static double add(double a, double b) { return a + b; } static double subtract(double a, double b) { return a - b; } static double multiply(double a, double b) { return a * b; } static double divide(double a, double b) { return a / b; } } public static void main(String[] args) { double a = 5.0; double b = 2.5; System.out.println(Calculator.add(a, b)); System.out.println(Calculator.subtract(a, b)); System.out.println(Calculator.multiply(a, b)); System.out.println(Calculator.divide(a, b)); } Usage
  • 14. Anonymous Function Calls ● Syntax – parameter ­> expression – Translates to ● function(parameter) where function implementation contains the expression – Parameter syntax, ● Parenthesis optional only for single parameters in function call. ● Parameter types are optional. – Expression syntax ● Braces and return required for multi-line expressions. ● Expressions can be method references.
  • 15. Functional Interfaces ● Specifying type of lambda expressions. – To assign lambda expressions to variables and used repeated. – To declare lambda expressions as function parameters. ● Standard Java interfaces with following exceptions, – Only one abstract method in the interface. ● SAM (Single Abstract Method) interfaces. – Can be decorated with annotation @FunctionalInterface for compiler to check that interface is SAM interface. ● Functional interfaces for common use cases already specified in java.util.function package. – Custom functional interfaces rarely required.
  • 16. Lambda Expression - Example // BiFunction takes two arguments and returns the result. // The following statement effectively creates an anonymous // class implementing BiFunction where the apply method adds the // two arguments and returns the result. BiFunction<Integer, Integer, Integer> intAdder = (a, b) -> a + b; int op1 = 5; int op2 = 25; int sum = intAdder.apply(op1, op2); System.out.printf("%d + %d = %dn", op1, op2, sum);
  • 17. Lambda Expression - Example public static void main(String[] args) { int op1 = 25; int op2 = 5; int sum = process(op1, op2, (a, b) -> a + b); int diff = process(op1, op2, (a, b) -> a - b); int product = process(op1, op2, (a, b) -> a * b); int div = process(op1, op2, (a, b) -> a / b); System.out.printf("%d + %d = %dn", op1, op2, sum); System.out.printf("%d - %d = %dn", op1, op2, diff); System.out.printf("%d * %d = %dn", op1, op2, product); System.out.printf("%d / %d = %dn", op1, op2, div); } private static int process( int x, int y, BiFunction<Integer, Integer, Integer> processor) { return processor.apply(x, y); }
  • 18. Lambda Expression - Example public class FunctionalCalculator { public static void main(String[] args) { if (args.length == 3) { Map<String, BiFunction<Double, Double, Double>> calculator = new HashMap<>(); calculator.put("+", (a, b) -> a + b); calculator.put("-", (a, b) -> a - b); calculator.put("*", (a, b) -> a * b); calculator.put("/", (a, b) -> a / b); String operator = args[1]; if (calculator.containsKey(operator)) { Double operand1 = Double.parseDouble(args[0]); Double operand2 = Double.parseDouble(args[2]); double result = calculator.get(operator).apply(operand1, operand2); System.out.printf("%.2f %s %.2f = %.2f", operand1, operator, operand2, result); } else { System.out.printf("Operator %s not recognisedn", operator); System.out.println("Operators:: +, -, *, /"); } } else { System.out.println("USAGE:: Command line arguments operand1 operator operand2"); System.out.println("Operators:: +, -, *, /"); } } }
  • 19. Closure ● Lambda expressions allow capturing variables and methods defined in their scope. – Lambda expressions close over the scope in which they exist. ● The state of the variables captured stay with the expressions even if they are passed to other methods and executed there. ● Captured variables are effectively final, i.e., – Mutating these values results in a compilation error.
  • 20. Closure-Example public class WeightCalculator { final double mass; public WeightCalculator(double mass) { this.mass = mass; } public Function<Double, Double> getCalculator() { return g -> this.getWeight(mass, g); } private double getWeight(double m, double g) { return m * g; } } public static void main(String[] args) { double mass = 10; Function<Double, Double> calculator = new WeightCalculator(mass).getCalculator(); double weightOnEarth = calculator.apply(9.8); double weightOnMars = calculator.apply(3.77); System.out.printf("%.2f kg on Earth is %.2f N on Earthn", mass, weightOnEarth); System.out.printf("%.2f kg on Earth is %.2f N on Marsn", mass, weightOnMars); }
  • 21. Method Referencing ● Obtaining the reference of a method so that – It can be assigned to a matching functional interface variable, – And that functional interface can be executed later. ● :: is the referencing operator. ● Applies to, – Static methods, e.g., ClassName::staticMethodName. – Instance methods, e.g., ObjectRef::instanceMethodName. – Constructors, e.g., ClassName::new.
  • 22. MethodReferencing- Example public class Doubler { public static double doubleIt(double value) { return 2 * value; } } public static void main(String[] args) { Function<Double, Double> doubler = Doubler::doubleIt; Consumer<String> printer = System.out::println; Function<Double, Double> maker = Double::new; workIt(doubler, printer, maker, 3); } private static void workIt( Function<Double, Double> worker, Consumer<String> consumer, Function<Double, Double> creater, double value) { double result = worker.apply(value); consumer.accept(creater.apply(result).toString()); }
  • 24. Optional ● Container class that may or may not contain a non- null value. ● Contains methods that – determine presence or absence of value. – perform operations based on presence or absence of a value. – operate on the contained value. ● Protects against NullPointerException.
  • 25. Key Members ● Construction using static factory methods, – empty() ● returns an empty Optional instance. – of(T value)  ● returns an Optional instance with value. – ofNullable(T value) ● returns an Optional instance with the supplied value if non- nullable, an empty instance otherwise.
  • 26. Key Members ● Accessors, – get()  ● returns contained value or throws NoSuchElementException if empty. – isPresent() ● returns true if not empty. – orElse(T other)  ● returns enclosed value if not empty otherwise returns other. – orElseGet(Supplier<? extends T> other) ● returns enclosed value if not empty otherwise calls other to get a value.
  • 27. Key Members ● Transformation, consumer and filter, – ifPresent(Consumer<? super T> consumer)  ● calls consumer on value if present otherwise does nothing. – filter(Predicate<? super T> predicate)  ● returns this Optional if the value is present and predicate returns true otherwise returns empty Optional. – map(Function<? super T, ? extends U> mapper)  ● transforms the value using the mapper if present otherwise does nothing. – flatMap(Function<? super T, Optional<U>>  mapper) ● applies mapper to value and returns an Optional bearing transformed value.
  • 28. Optional-Example /** * Find at matching name from the list and if present. print the value * after converting it into uppercase. * @param args */ public static void main(String[] args) { List<String> names = Arrays.asList("George Patton", "Omar Bradley", "Bernard Montgomery", "Erwin Romel"); Optional<String> name = find(names, "Brad"); name.map(x -> x.toUpperCase()).ifPresent(x -> System.out.println(x)); System.out.println("DONE"); } private static Optional<String> find(List<String> names, String value) { Optional<String> result = Optional.empty(); boolean found = false; Iterator<String> itr = names.iterator(); while (!found && itr.hasNext()) { String item = itr.next(); if (item.contains(value)) { found = true; result = Optional.of(item); } } return result; }
  • 30. Streams ● An abstraction allowing generic and declarative processing of collections. ● Operations on streams are – Intermediate operations ● Return a stream object representing intermediate results. ● Allow chaining of operations. – Terminal operations ● Either perform a void operation or return a non-stream result. ● Immutable operations – Original data source is not modified.
  • 31. Streams ● Obtaining a stream on a collection, – stream() to return a sequential stream. – parallelStream() to create a stream capable of executing in multiple threads. ● Streams evaluated lazily, – Once a terminal operation is executed. ● Streams cannot be reused, – Once a terminal operation executed, the stream is closed. – Call get() on the stream before calling a terminal operation to get a copy of the stream.
  • 32. Streams - Example public class Finder { /** * Find at matching name from the list and if present. print the * value after converting it into uppercase. * @param args */ public static void main(String[] args) { List<String> names = Arrays.asList("George Patton", "Omar Bradley", "Bernard Montgomery", "Erwin Romel"); Optional<String> name = names.stream(). filter(x -> x.contains("Bernard")).findFirst(); name.map(x -> x.toUpperCase()). ifPresent(x -> System.out.println(x)); System.out.println("Done"); } }
  • 33. Collectors ● Implementation of the Collector interface. ● Performs useful reduction operations on stream, e.g., – Accumulation of elements into collections, – Summarising values, – Grouping, – Partitioning ● Typically used in the collect method of the stream to return the final collection after the stream pipeline has executed.
  • 34. Collectors - Example /** * Return a list of even numbers from a list of string * representation of integers. * @param args */ List<String> numStr = Arrays.asList("53", "26", "33", "77", "2", "8", "9", "98"); List<Integer> evenNums = numStr.stream(). map(x -> Integer.parseInt(x)). filter(x -> x % 2 == 0). collect(Collectors.toList()); evenNums.forEach(System.out::println);
  • 35. Stream Reduction - Example List<Double> nums = Arrays.asList(25.5, 23.25, 17.0, 9.25); /* * reduce takes an initial accumulator value and a BiFunction * extension that takes the accumulated value, iteratively adds * the elements in the stream. */ double average = nums.stream(). reduce(0.0, (acc, x) -> acc + x)/nums.size(); System.out.printf("Average = %.3f", average);
  • 36. Collector Reduction - Example List<Double> nums = Arrays.asList(25.5, 23.25, 17.0, 9.25); double average = nums.stream(). collect(Collectors.averagingDouble(x -> x)); System.out.printf("Average = %.3f", average);
  • 37. Creating Streams ● static Stream<T> of(T... values) – Creates a stream of values specified. ● static  IntStream range(int inclusiveStart,  int exclusiveEnd) – Sequentially ordered stream of integers with increment of 1 excluding the end value. ● static IntStream rangeClosed(int  inclusiveStart, int inclusiveEnd) – Sequentially ordered stream of integers with increment of 1 including the end value.
  • 38. IntStream - Example IntStream range = IntStream.rangeClosed(1, num); int factorial = range.reduce(1, (acc, x) -> acc * x); System.out.printf("%d! = %dn", num, factorial);
  • 40. flatMap ● Consider a collection of collections of items. – flatMap used to transform items of inner collections. – and then flatten the collection of collections of transformed items to a collection of transformed items. ● Defined for – Stream, – Optional
  • 41. Example – Stream flatMap List<List<String>> linesOfWords = Arrays.asList(Arrays.asList("Incy", "wincy", "spider"), Arrays.asList("Climbing", "up", "the", "spout")); Stream<String> dataStream = linesOfWords.stream(). flatMap(line -> line.stream().map(word -> word.toUpperCase())); List<String> data = dataStream.collect(Collectors.toList()); data.forEach(System.out::println); INCY WINCY SPIDER CLIMBING UP THE SPOUT
  • 42. Example – Flattening Optional Collections List<Optional<Integer>> nums = Arrays.asList(Optional.of(3), Optional.of(5), Optional.empty(), Optional.of(9)); System.out.println(nums); List<Integer> filteredNums = nums.stream(). filter(n -> n.isPresent()). map(n -> n.get()). collect(Collectors.toList()); System.out.println(filteredNums); [Optional[3], Optional[5], Optional. empty, Optional[9]] [3, 5, 9]