SlideShare uma empresa Scribd logo
1 de 49
Baixar para ler offline
Lambda Functions in Java 8
Ganesh Samarthyam
ganesh.samarthyam@gmail.com
www.designsmells.com
@GSamarthyam
Java is evolving…
Lambdas added in Java 8
Java 8 streams (and parallel streams):
Excellent example of applying functional
programming in practice
One-liner #1
Files.lines(Paths.get("FileRead.java")).forEach(System.out::println);
This code prints the contents of
the file “FileRead.java” in the
current directory
One-liner #2
Pattern.compile(" ").splitAsStream("java 8 streams").forEach(System.out::println);
This code splits the input string “java 8
streams” based on whitespace and hence
prints the strings “java”, “8”, and
“streams” on the console
One-liner #3
new Random().ints().limit(5).forEach(System.out::println);
Generates 5 random integers and prints
them on the console
One-liner #4
"hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch));
Extracts characters in the string “hello”,
sorts the chars and prints the chars
Productive programming with lambdas
Productive programming with lambdas
public static void main(String []file) throws Exception {
// process each file passed as argument
// try opening the file with FileReader
try (FileReader inputFile = new FileReader(file[0])) {
int ch = 0;
while( (ch = inputFile.read()) != -1) {
// ch is of type int - convert it back to char
System.out.print( (char)ch );
}
}
// try-with-resources will automatically release FileReader object
}
public static void main(String []file) throws Exception {
// read the file line-by-line and print it on the console
Files.lines(Paths.get(file[0])).forEach(System.out::println);
}
Functional programming in Java 8
What is different with functional programming?
if
while
for
switch
Perspective - for loops!
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
for(String string : strings) {
System.out.println(string);
}
External Iteration
Perspective - for loops!
Arrays.asList("eeny", "meeny", "miny", “mo”)
.forEach(string -> System.out.println(string));
Internal Iteration
Perspective - for loops!
Arrays.asList("eeny", "meeny", "miny", “mo”)
.forEach(string -> System.out.println(string));
Internal Iteration
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
for(String string : strings) {
System.out.println(string);
}
External Iteration
Lambda
expression
Perspective - for loops!
Arrays.asList("eeny", "meeny", "miny", “mo”)
.forEach(string -> System.out.println(string));
Internal Iteration
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
for(String string : strings) {
System.out.println(string);
}
External Iteration
Procedural
approach
Functional
approach
Let’s get started!
Introducing lambdas
Lambdas
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Lambda
functions!
Lambdas
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Capture in a
variable
Execute later
What are lambda functions?
❖ (Java 8) One way to think about lambdas is
“anonymous function” or “unnamed function” - they
are functions without a name and are not associated
with any class
❖ Functions don’t change external state
What is functional programming?
❖ Functions are entities that accepts input(s) and produces
an output
Underlying approach:
“Evaluate an expression.
Then use the results for
something else.”
Composing functions
❖ Functions are connected together by their outputs to
other functions’ inputs
sediment
pre-
carbon
ultra-filter
post-
carbon
Filtered
water
Let’s get our hands dirty!
❖ Make sure you have JDK 8
installed
❖ Try out the programs in your
machine (using IDE of your
choice)
Java 8 lambdas - “Hello world!”
interface LambdaFunction {
void call();
}
class FirstLambda {
public static void main(String []args) {
LambdaFunction lambdaFunction = () -> System.out.println("Hello world");
lambdaFunction.call();
}
}
Java 8 lambdas - “Hello world!”
interface LambdaFunction {
void call();
}
class FirstLambda {
public static void main(String []args) {
LambdaFunction lambdaFunction = () -> System.out.println("Hello world");
lambdaFunction.call();
}
}
Functional interface - provides
signature for lambda functions
Lambda function/expression
Call to the lambda
Prints “Hello world” on the console when executed
Parts of a lambda expression
() -> System.out.println("Hello world");
No parameters, i.e., ()
Arrow operator that separates
parameters and the body
The lambda body
Return type “void” inferred from the body
Functional interfaces
@FunctionalInterface
interface LambdaFunction {
void call();
}
Functional interface
Abstract method providing the signature of the
lambda function
Annotation to explicitly state that it is a functional
interface
Older Single Abstract Methods (SAMs)
// in java.lang package
interface Runnable { void run(); }
// in java.util package
interface Comparator<T> { boolean compare(T x, T y); }
// java.awt.event package:
interface ActionListener { void actionPerformed(ActionEvent e) }
// java.io package
interface FileFilter { boolean accept(File pathName); }
Default methods in interfaces
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
“Diamond” inheritance problem?
“Diamond” inheritance problem?
interface Interface1 {
default public void foo() { System.out.println("Interface1’s foo"); }
}
interface Interface2 {
default public void foo() { System.out.println("Interface2’s foo"); }
}
public class Diamond implements Interface1, Interface2 {
public static void main(String []args) {
new Diamond().foo();
}
}
Error:(9, 8) java: class Diamond inherits unrelated defaults for foo()
from types Interface1 and Interface2
“Diamond” inheritance problem?
interface Interface1 {
default public void foo() { System.out.println("Interface1’s foo"); }
}
interface Interface2 {
default public void foo() { System.out.println("Interface2’s foo"); }
}
public class Diamond implements Interface1, Interface2 {
public void foo() { Interface1.super.foo(); }
public static void main(String []args) {
new Diamond().foo();
}
}
Add this definition
to resolve the
ambiguity
“Diamond” inheritance problem?
class BaseClass {
public void foo() { System.out.println("BaseClass’s foo"); }
}
interface BaseInterface {
default public void foo() { System.out.println("BaseInterface’s foo”); }
}
public class Diamond extends BaseClass implements BaseInterface {
public static void main(String []args) {
new Diamond().foo();
}
}
Compiles cleanly; Java 8
rules help deal with the
diamond problem
Using built-in functional interfaces
// within Iterable interface
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
// in java.util.function package
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
// the default andThen method elided
}
Using built-in functional interfaces
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.forEach(string -> System.out.println(string));
Built-in interfaces
Predicate<T> Checks a condition and returns a
boolean value as result
In filter() method in
java.util.stream.Stream
which is used to remove elements
in the stream that don’t match the
given condition (i.e., predicate) asConsumer<T> Operation that takes an argument but
returns nothing
In forEach() method in
collections and in
java.util.stream.Stream; this
method is used for traversing all
the elements in the collection orFunction<T,
R>
Functions that take an argument and
return a result
In map() method in
java.util.stream.Stream to
transform or operate on the passed
value and return a result.
Supplier<T> Operation that returns a value to the
caller (the returned value could be
same or different values)
In generate() method in
java.util.stream.Stream to
create a infinite stream of
elements.
Built-in interfaces
Method references
Method references - “syntactic sugar” for lambda
functions
They “route” function parameters
arg -> System.out.println(arg)
System.out::println
Method references
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
Method
reference
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
Method references
Cannot use method references when lambda functions do
more than“routing” function parameters
strings.forEach(string -> System.out.println(string.toUpperCase()));
More processing here than just
“routing” parameters
Method references
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
public static void printUpperCaseString(String string) {
System.out.println(string.toUpperCase());
}
strings.forEach(MethodReference::printUpperCaseString);
“Effectively final” variables
import java.util.Arrays;
import java.util.List;
class PigLatin {
public static void main(String []args) {
String suffix = "ay";
List<String> strings = Arrays.asList("one", "two", "three", "four");
strings.forEach(string -> System.out.println(string + suffix));
}
} Accessing “local variable” suffix
here; hence it is considered
“effectively final”
“Effectively final” variables
import java.util.Arrays;
import java.util.List;
class PigLatin {
public static void main(String []args) {
String suffix = "ay";
List<String> strings = Arrays.asList("one", "two", "three", “four");
suffix = "e"; // assign to suffix variable
strings.forEach(string -> System.out.println(string + suffix));
}
}
PigLatinAssign.java:9: error: local variables referenced from a
lambda expression must be final or effectively final
strings.forEach(string -> System.out.println(string + suffix));
^
1 error
Wrap-up: example using streams
import java.util.stream.*;
import java.nio.file.*;
import java.util.*;
import java.nio.charset.Charset;
import java.io.IOException;
class ReadFile {
public static void main(String []args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("./Ulysses.txt"),
Charset.defaultCharset());
Map<Integer, List<String>> wordGroups
= lines.parallelStream()
.map(line -> line.replaceAll("W", " ").split(" "))
.flatMap(Arrays::stream)
.filter(str -> str.length() > 7)
.distinct()
.sorted()
.collect(Collectors.groupingBy(String::length));
wordGroups.forEach( (count, words) -> {
System.out.printf("word(s) of length %d %n", count);
words.forEach(System.out::println); });
}
}
Lists words organised by
their length in the novel
“Ulysses.txt”
Adapt: Learn functional
programming
Check out our book!
❖ Programming examples are
from our book:
❖ Oracle Certified Professional
Java SE 8 Programmer Exam
1Z0-809: A Comprehensive
OCPJP 8 Certification Guide,
S.G. Ganesh, Hari Kiran
Kumar, Tushar Sharma, Apress,
2016.
❖ Website: ocpjava.wordpress.com
www.designsmells.com bit.ly/sgganesh @GSamarthyam

Mais conteúdo relacionado

Mais procurados

New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statementmanish kumar
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 

Mais procurados (20)

Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Java generics
Java genericsJava generics
Java generics
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Core java
Core javaCore java
Core java
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 

Destaque

Building a serverless app
Building a serverless appBuilding a serverless app
Building a serverless appVinay Krishna
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native DevelopmentCodeOps Technologies LLP
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture CodeOps Technologies LLP
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkCodeOps Technologies LLP
 
AngularJS Anatomy & Directives
AngularJS Anatomy & DirectivesAngularJS Anatomy & Directives
AngularJS Anatomy & DirectivesDigikrit
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle IntroductionGanesh Samarthyam
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Heartin Jacob
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryMurughan Palaniachari
 

Destaque (20)

Overview of Microservices
Overview of MicroservicesOverview of Microservices
Overview of Microservices
 
Building a serverless app
Building a serverless appBuilding a serverless app
Building a serverless app
 
Mongo db
Mongo dbMongo db
Mongo db
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native Development
 
7 best quotes on dev ops
7 best quotes on dev ops7 best quotes on dev ops
7 best quotes on dev ops
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture
 
Better java with design
Better java with designBetter java with design
Better java with design
 
Introduction to chef
Introduction to chefIntroduction to chef
Introduction to chef
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
 
Angular js
Angular jsAngular js
Angular js
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
AngularJS Anatomy & Directives
AngularJS Anatomy & DirectivesAngularJS Anatomy & Directives
AngularJS Anatomy & Directives
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous Delivery
 
DevOps Toolchain v1.0
DevOps Toolchain v1.0DevOps Toolchain v1.0
DevOps Toolchain v1.0
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 

Semelhante a Lambda Functions in Java 8

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)KonfHubTechConferenc
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8franciscoortin
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsCodeOps Technologies LLP
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8James Brown
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
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
 
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
 

Semelhante a Lambda Functions in Java 8 (20)

Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
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...
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
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
 

Mais de Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 

Mais de Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 

Último

Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 

Último (20)

Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 

Lambda Functions in Java 8

  • 1. Lambda Functions in Java 8 Ganesh Samarthyam ganesh.samarthyam@gmail.com www.designsmells.com @GSamarthyam
  • 4. Java 8 streams (and parallel streams): Excellent example of applying functional programming in practice
  • 5. One-liner #1 Files.lines(Paths.get("FileRead.java")).forEach(System.out::println); This code prints the contents of the file “FileRead.java” in the current directory
  • 6. One-liner #2 Pattern.compile(" ").splitAsStream("java 8 streams").forEach(System.out::println); This code splits the input string “java 8 streams” based on whitespace and hence prints the strings “java”, “8”, and “streams” on the console
  • 8. One-liner #4 "hello".chars().sorted().forEach(ch -> System.out.printf("%c ", ch)); Extracts characters in the string “hello”, sorts the chars and prints the chars
  • 10. Productive programming with lambdas public static void main(String []file) throws Exception { // process each file passed as argument // try opening the file with FileReader try (FileReader inputFile = new FileReader(file[0])) { int ch = 0; while( (ch = inputFile.read()) != -1) { // ch is of type int - convert it back to char System.out.print( (char)ch ); } } // try-with-resources will automatically release FileReader object } public static void main(String []file) throws Exception { // read the file line-by-line and print it on the console Files.lines(Paths.get(file[0])).forEach(System.out::println); }
  • 12. What is different with functional programming? if while for switch
  • 13. Perspective - for loops! List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration
  • 14. Perspective - for loops! Arrays.asList("eeny", "meeny", "miny", “mo”) .forEach(string -> System.out.println(string)); Internal Iteration
  • 15. Perspective - for loops! Arrays.asList("eeny", "meeny", "miny", “mo”) .forEach(string -> System.out.println(string)); Internal Iteration List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration Lambda expression
  • 16. Perspective - for loops! Arrays.asList("eeny", "meeny", "miny", “mo”) .forEach(string -> System.out.println(string)); Internal Iteration List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); for(String string : strings) { System.out.println(string); } External Iteration Procedural approach Functional approach
  • 19. Lambdas List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); Lambda functions!
  • 20. Lambdas List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); Capture in a variable Execute later
  • 21. What are lambda functions? ❖ (Java 8) One way to think about lambdas is “anonymous function” or “unnamed function” - they are functions without a name and are not associated with any class ❖ Functions don’t change external state
  • 22. What is functional programming? ❖ Functions are entities that accepts input(s) and produces an output Underlying approach: “Evaluate an expression. Then use the results for something else.”
  • 23. Composing functions ❖ Functions are connected together by their outputs to other functions’ inputs sediment pre- carbon ultra-filter post- carbon Filtered water
  • 24. Let’s get our hands dirty! ❖ Make sure you have JDK 8 installed ❖ Try out the programs in your machine (using IDE of your choice)
  • 25. Java 8 lambdas - “Hello world!” interface LambdaFunction { void call(); } class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } }
  • 26. Java 8 lambdas - “Hello world!” interface LambdaFunction { void call(); } class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } } Functional interface - provides signature for lambda functions Lambda function/expression Call to the lambda Prints “Hello world” on the console when executed
  • 27. Parts of a lambda expression () -> System.out.println("Hello world"); No parameters, i.e., () Arrow operator that separates parameters and the body The lambda body Return type “void” inferred from the body
  • 28. Functional interfaces @FunctionalInterface interface LambdaFunction { void call(); } Functional interface Abstract method providing the signature of the lambda function Annotation to explicitly state that it is a functional interface
  • 29. Older Single Abstract Methods (SAMs) // in java.lang package interface Runnable { void run(); } // in java.util package interface Comparator<T> { boolean compare(T x, T y); } // java.awt.event package: interface ActionListener { void actionPerformed(ActionEvent e) } // java.io package interface FileFilter { boolean accept(File pathName); }
  • 30. Default methods in interfaces public interface Iterator<E> { boolean hasNext(); E next(); default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
  • 32. “Diamond” inheritance problem? interface Interface1 { default public void foo() { System.out.println("Interface1’s foo"); } } interface Interface2 { default public void foo() { System.out.println("Interface2’s foo"); } } public class Diamond implements Interface1, Interface2 { public static void main(String []args) { new Diamond().foo(); } } Error:(9, 8) java: class Diamond inherits unrelated defaults for foo() from types Interface1 and Interface2
  • 33. “Diamond” inheritance problem? interface Interface1 { default public void foo() { System.out.println("Interface1’s foo"); } } interface Interface2 { default public void foo() { System.out.println("Interface2’s foo"); } } public class Diamond implements Interface1, Interface2 { public void foo() { Interface1.super.foo(); } public static void main(String []args) { new Diamond().foo(); } } Add this definition to resolve the ambiguity
  • 34. “Diamond” inheritance problem? class BaseClass { public void foo() { System.out.println("BaseClass’s foo"); } } interface BaseInterface { default public void foo() { System.out.println("BaseInterface’s foo”); } } public class Diamond extends BaseClass implements BaseInterface { public static void main(String []args) { new Diamond().foo(); } } Compiles cleanly; Java 8 rules help deal with the diamond problem
  • 35. Using built-in functional interfaces // within Iterable interface default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } // in java.util.function package @FunctionalInterface public interface Consumer<T> { void accept(T t); // the default andThen method elided }
  • 36. Using built-in functional interfaces List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string));
  • 37. Built-in interfaces Predicate<T> Checks a condition and returns a boolean value as result In filter() method in java.util.stream.Stream which is used to remove elements in the stream that don’t match the given condition (i.e., predicate) asConsumer<T> Operation that takes an argument but returns nothing In forEach() method in collections and in java.util.stream.Stream; this method is used for traversing all the elements in the collection orFunction<T, R> Functions that take an argument and return a result In map() method in java.util.stream.Stream to transform or operate on the passed value and return a result. Supplier<T> Operation that returns a value to the caller (the returned value could be same or different values) In generate() method in java.util.stream.Stream to create a infinite stream of elements.
  • 39. Method references Method references - “syntactic sugar” for lambda functions They “route” function parameters arg -> System.out.println(arg) System.out::println
  • 40. Method references List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = System.out::println; strings.forEach(printString); Method reference List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString);
  • 41. Method references Cannot use method references when lambda functions do more than“routing” function parameters strings.forEach(string -> System.out.println(string.toUpperCase())); More processing here than just “routing” parameters
  • 42. Method references List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = System.out::println; strings.forEach(printString); public static void printUpperCaseString(String string) { System.out.println(string.toUpperCase()); } strings.forEach(MethodReference::printUpperCaseString);
  • 43. “Effectively final” variables import java.util.Arrays; import java.util.List; class PigLatin { public static void main(String []args) { String suffix = "ay"; List<String> strings = Arrays.asList("one", "two", "three", "four"); strings.forEach(string -> System.out.println(string + suffix)); } } Accessing “local variable” suffix here; hence it is considered “effectively final”
  • 44. “Effectively final” variables import java.util.Arrays; import java.util.List; class PigLatin { public static void main(String []args) { String suffix = "ay"; List<String> strings = Arrays.asList("one", "two", "three", “four"); suffix = "e"; // assign to suffix variable strings.forEach(string -> System.out.println(string + suffix)); } } PigLatinAssign.java:9: error: local variables referenced from a lambda expression must be final or effectively final strings.forEach(string -> System.out.println(string + suffix)); ^ 1 error
  • 45. Wrap-up: example using streams import java.util.stream.*; import java.nio.file.*; import java.util.*; import java.nio.charset.Charset; import java.io.IOException; class ReadFile { public static void main(String []args) throws IOException { List<String> lines = Files.readAllLines(Paths.get("./Ulysses.txt"), Charset.defaultCharset()); Map<Integer, List<String>> wordGroups = lines.parallelStream() .map(line -> line.replaceAll("W", " ").split(" ")) .flatMap(Arrays::stream) .filter(str -> str.length() > 7) .distinct() .sorted() .collect(Collectors.groupingBy(String::length)); wordGroups.forEach( (count, words) -> { System.out.printf("word(s) of length %d %n", count); words.forEach(System.out::println); }); } } Lists words organised by their length in the novel “Ulysses.txt”
  • 46.
  • 48. Check out our book! ❖ Programming examples are from our book: ❖ Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809: A Comprehensive OCPJP 8 Certification Guide, S.G. Ganesh, Hari Kiran Kumar, Tushar Sharma, Apress, 2016. ❖ Website: ocpjava.wordpress.com