SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Software
Engineering
Computer Science
Engineering School
Francisco Ortin University of Oviedo
New Functional Features
of Java 8
Francisco Ortín Soler
Disclaimer
• This slides are aimed at briefly explaining the new
functional features of Java 8
• It is an informal document
• The code used in this slides is available at
http://www.reflection.uniovi.es/download/2014/java8.zip
• It has been compiled and executed with Java SE
Development Kit 8.0
March 20th, 2014
Francisco Ortin
ortin at lsi.uniovi.es
Francisco Ortín Soler
Java 8
• Java 8 has been released on March 2014
• It includes some features of the functional
paradigm such as:
 Lambda expressions
 Method references
 Types of some typical lambda expressions
 Streams (aggregate operations)
 Closures (constant variables of the enclosing block)
• It also provides default method implementations
for interfaces
Francisco Ortín Soler
Lambda Expressions
• Lambda expressions are provided
 The -> symbol separates parameters from body
 Parameter types can be optionally specified
 Parenthesis are not mandatory when only one
parameter is passed
 If the body is just one expression, return and { }
are not required
String[] words = new String [] {
"Hello", "from", "Java", "8" };
Arrays.sort(words,
(word1, word2) -> word1.length() - word2.length()
);
Francisco Ortín Soler
Types of Lambda Expressions
• Lambda expressions promote to interfaces with
one abstract method with the same signature as
the lambda expression
• This kind of interfaces are called Functional
Interfaces
 The @FunctionalInterface annotation can be used
 It is optional; helpful for detecting errors
@FunctionalInterface // not mandatory
interface MyPredicate<T> {
boolean exec(T element);
}
Francisco Ortín Soler
Types of Lambda Expressions
@FunctionalInterface // not mandatory
interface MyPredicate<T> {
boolean exec(T element);
}
class Promotion {
static <T> T find(T[] collection, MyPredicate<T> predicate) {
for(T item : collection)
if (predicate.exec(item))
return item;
return null;
}
public static void main(String... args) {
Integer[] numbers = new Integer [] { 1, 2, 3 };
int number = find(numbers, n -> n % 2 == 0);
System.out.println(number);
}
}
Francisco Ortín Soler
Method References
• Sometimes, a lambda expression does nothing but calling
an existing method
• In those cases, the existing method can be referred by
name
• For this purpose, the :: operator has been added to Java 8
• Static (class) methods are referred with Class::method
class MethodReferences {
static boolean isOdd(Integer number) {
return number %2 != 0;
}
public static void main(String... args) {
Integer[] numbers = new Integer [] { 1, 2, 3 };
Integer number = Promotion.find(numbers, MethodReferences::isOdd);
number = Promotion.find(numbers, new EqualTo(3)::compare);
}
}
Francisco Ortín Soler
Method References
• Instance methods are referred with object::method
• Since these methods are associated to an object (this),
they can be stateful
class EqualTo {
private int value;
public EqualTo(int value) { this.value = value; }
public boolean compare(Integer n) { return value == n; }
}
public class MethodReferences {
public static void main(String... args) {
Integer[] numbers = new Integer [] { 1, 2, 3 };
Integer number = Promotion.find(numbers,
new EqualTo(3)::compare);
}
}
Francisco Ortín Soler
Types of Typical Lambda Exprs
• The package java.util.function provides types
(functional interfaces) of typical lambda functions
 Function<T,R>: Function that receives a T argument
and returns a R result
 Predicate<T>: Predicate of one T argument
 Consumer<T>: An operation that accepts a single T
argument and returns no result
 Supplier<T>: Function with no parameter returning
a T value
 UnaryOperator<T>: Operation on a single T operand,
producing a T result
 BinaryOperator<T>: Operation upon two T
operands, producing a result of the same type as
the operands
Francisco Ortín Soler
Types of Typical Lambda Exprs
• Notice: the methods of the interfaces must be explicitly called, and
they are named differently (test, accept, apply, get…)
public static void main(String... args) {
MyPredicate<Integer> even = n -> n%2 == 0; // my own type
Predicate<Integer> odd = n -> n%2 != 0;
System.out.println(even.exec(number) + " " + odd.test(number));
Consumer<Integer> printAction = n -> System.out.println(n);
printAction.accept(number);
Function<Integer,Double> sqrt = n -> Math.sqrt(n);
System.out.println(sqrt.apply(number));
Supplier<Integer> random = () -> (int)(Math.random()*1000 - 1000/2);
System.out.println(random.get());
BinaryOperator<Integer> times = (a,b) -> a*b;
System.out.printf(times.apply(3,2));
Francisco Ortín Soler
Types of Typical Lambda Exprs
• Since generics is implemented in Java with type
erasure (i.e., T is Object), the previous types
have specific versions for built-in types:
And more…
http://download.java.net/jdk8/docs/api/java/util/function/package-summary.html
Predicate<T> Supplier<T> Consumer<T> Function<T,R>
DoublePredicate BooleanSupplier DoubleConsumer DoubleFunction<R>
IntPredicate DoubleSupplier IntConsumer IntFunction<R>
LongPredicate IntSupplier LongConsumer IntToDoubleFunction
LongSupplier IntToLongFunction
LongFunction<R>
…
Francisco Ortín Soler
Streams with Aggregate Operations
• The new java.util.stream package provides an API to
support functional-style operations on streams
• A stream is a sequence of elements
 It is not a data structure that stores elements (i.e. a
collection)
• They support sequential and parallel functional-style
aggregate operations
• Operations are composed into a stream pipeline
• Pipeline consists of
 A source (array, collection, generator, I/O channel…)
 Intermediate aggregate operations
 And a terminal operation, producing a result
• Computation on the source data is only performed when
the terminal operation is initiated (kind of lazy)
Francisco Ortín Soler
Streams (Aggregate Operations)
public class Streams {
static int compute(Collection<Integer> collection) {
return collection.stream()
.filter(n -> n%2 == 0) // even numbers
.map(n -> n*n) // square
.reduce(0, (acc, item) -> acc + item); // summation
}
public static void main(String... args) {
System.out.println(compute(Arrays.asList(1, 2, 3, 4, 5)));
System.out.println(Arrays.asList(
Stream.iterate(1, n -> n+1)
.skip(10)
.limit(5)
.toArray(Integer[]::new)
));
}
}
source
aggregate operations
terminal operation
source (infinite)
aggregate operations
terminal operation
• Similar to .NET LINQ
• There will be database streams eventually?
Francisco Ortín Soler
Closures
• Lambda expressions can capture variables of the
enclosing scope
• They do not have shadowing issues (a new scope is not
created, being lexically scoped)
• Captured variables must be final or effectively final (their
value cannot be modified)
public class Closures {
static Function<Integer,Integer> createClosure(int initialValue) {
int number = initialValue; // must be constant
return n -> number + n;
}
public static void main(String... args) {
Function<Integer,Integer> closure1 = createClosure(1);
System.out.println(closure1.apply(7) );
Function<Integer,Integer> closure10 = createClosure(10);
System.out.println(closure10.apply(7) );
}
}
Francisco Ortín Soler
Closures
• Since functions are objects, they can represent functions
with a mutable state
class Fibonacci implements Supplier<Integer> {
private int previous = 0, current = 1;
@Override
public Integer get() {
int next = current + previous;
previous = current;
current = next;
return previous;
}
public static void main(String... args) {
System.out.println(Arrays.asList(
Stream.generate(new Fibonacci()).limit(10)
.toArray(Integer[]::new)
));
}
}
Francisco Ortín Soler
Default Methods
• Java 8 provides default implementations for interface
methods (the default keyword is used), similar to mixins
@FunctionalInterface interface Comparator<T> {
int compare(T a, T b);
default Comparator<T> reversed() { return (a, b) -> this.compare(b,a); }
}
public class DefaultMethods {
public static <T> T max(T a, T b, Comparator<T> comp) {
return comp.compare(a,b)<0 ? a : b;
}
public static <T> T min(T a, T b, Comparator<T> comp) {
return max(a, b, comp.reversed());
}
public static void main(String... args) {
Comparator<String> comparator = (a,b) -> a.length() - b.length();
System.out.println(max("hello", "bye", comparator));
System.out.println(min("hello", "bye", comparator));
} }
Francisco Ortín Soler
Multiple Inheritance
• As with multiple inheritance languages, different
implementations of the same method may be
inherited
• However, the Java compiler checks this condition,
reporting an error
interface A {
default void m() { System.out.println("A::m"); }
}
interface B {
default void m() { System.out.println("B::m"); }
}
public class MultipleInheritance
implements A, B { // compiler error
}
Francisco Ortín Soler
Multiple Inheritance
• Besides, a default method cannot be inherited if
the class implements another interface with that
method (even without a default implementation)
interface A {
default void m() { System.out.println("A::m"); }
}
interface C {
void m();
}
class MyClass implements A, C { // compiler error
}
Francisco Ortín Soler
Multiple Inheritance
• Java 8 allows diamond inheritance: the most
specific (derived) method implementation is called
interface A {
default void m() { System.out.println("A::m"); }
}
interface A1 extends A {}
interface A2 extends A {
default void m() { System.out.println("A2::m"); }
}
class Diamond implements A1, A2 {
public static void main(String... args) {
new Diamond().m(); // A2::m
A1 a1 = new Diamond();
a1.m();
} }
Francisco Ortín Soler
Static Methods
• Java 8 allows interfaces to implement static methods to
provide utility methods
• The static methods specific to an interface can be kept in
the same interface rather than in a separate class
@FunctionalInterface
interface Comparator<T> {
int compare(T a, T b);
static <T extends Comparable<T>> Comparator<T> naturalOrder() {
return (a,b) -> a.compareTo(b);
}
}
public class DefaultMethods {
public static void main(String... args) {
System.out.println(
max("hello", "bye", Comparator.naturalOrder()
));
} }
Software
Engineering
Computer Science
Engineering School
Francisco Ortin University of Oviedo
New Functional Features
of Java 8

Weitere ähnliche Inhalte

Was ist angesagt?

Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 

Was ist angesagt? (20)

Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Java generics
Java genericsJava generics
Java generics
 
Introduction to Erlang Part 1
Introduction to Erlang Part 1Introduction to Erlang Part 1
Introduction to Erlang Part 1
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Java operators
Java operatorsJava operators
Java operators
 
Introduction to Erlang Part 2
Introduction to Erlang Part 2Introduction to Erlang Part 2
Introduction to Erlang Part 2
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
02basics
02basics02basics
02basics
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 

Ähnlich wie New Functional Features of Java 8

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 

Ähnlich wie New Functional Features of Java 8 (20)

Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
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
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8
 
Java8
Java8Java8
Java8
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Kürzlich hochgeladen (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

New Functional Features of Java 8

  • 1. Software Engineering Computer Science Engineering School Francisco Ortin University of Oviedo New Functional Features of Java 8
  • 2. Francisco Ortín Soler Disclaimer • This slides are aimed at briefly explaining the new functional features of Java 8 • It is an informal document • The code used in this slides is available at http://www.reflection.uniovi.es/download/2014/java8.zip • It has been compiled and executed with Java SE Development Kit 8.0 March 20th, 2014 Francisco Ortin ortin at lsi.uniovi.es
  • 3. Francisco Ortín Soler Java 8 • Java 8 has been released on March 2014 • It includes some features of the functional paradigm such as:  Lambda expressions  Method references  Types of some typical lambda expressions  Streams (aggregate operations)  Closures (constant variables of the enclosing block) • It also provides default method implementations for interfaces
  • 4. Francisco Ortín Soler Lambda Expressions • Lambda expressions are provided  The -> symbol separates parameters from body  Parameter types can be optionally specified  Parenthesis are not mandatory when only one parameter is passed  If the body is just one expression, return and { } are not required String[] words = new String [] { "Hello", "from", "Java", "8" }; Arrays.sort(words, (word1, word2) -> word1.length() - word2.length() );
  • 5. Francisco Ortín Soler Types of Lambda Expressions • Lambda expressions promote to interfaces with one abstract method with the same signature as the lambda expression • This kind of interfaces are called Functional Interfaces  The @FunctionalInterface annotation can be used  It is optional; helpful for detecting errors @FunctionalInterface // not mandatory interface MyPredicate<T> { boolean exec(T element); }
  • 6. Francisco Ortín Soler Types of Lambda Expressions @FunctionalInterface // not mandatory interface MyPredicate<T> { boolean exec(T element); } class Promotion { static <T> T find(T[] collection, MyPredicate<T> predicate) { for(T item : collection) if (predicate.exec(item)) return item; return null; } public static void main(String... args) { Integer[] numbers = new Integer [] { 1, 2, 3 }; int number = find(numbers, n -> n % 2 == 0); System.out.println(number); } }
  • 7. Francisco Ortín Soler Method References • Sometimes, a lambda expression does nothing but calling an existing method • In those cases, the existing method can be referred by name • For this purpose, the :: operator has been added to Java 8 • Static (class) methods are referred with Class::method class MethodReferences { static boolean isOdd(Integer number) { return number %2 != 0; } public static void main(String... args) { Integer[] numbers = new Integer [] { 1, 2, 3 }; Integer number = Promotion.find(numbers, MethodReferences::isOdd); number = Promotion.find(numbers, new EqualTo(3)::compare); } }
  • 8. Francisco Ortín Soler Method References • Instance methods are referred with object::method • Since these methods are associated to an object (this), they can be stateful class EqualTo { private int value; public EqualTo(int value) { this.value = value; } public boolean compare(Integer n) { return value == n; } } public class MethodReferences { public static void main(String... args) { Integer[] numbers = new Integer [] { 1, 2, 3 }; Integer number = Promotion.find(numbers, new EqualTo(3)::compare); } }
  • 9. Francisco Ortín Soler Types of Typical Lambda Exprs • The package java.util.function provides types (functional interfaces) of typical lambda functions  Function<T,R>: Function that receives a T argument and returns a R result  Predicate<T>: Predicate of one T argument  Consumer<T>: An operation that accepts a single T argument and returns no result  Supplier<T>: Function with no parameter returning a T value  UnaryOperator<T>: Operation on a single T operand, producing a T result  BinaryOperator<T>: Operation upon two T operands, producing a result of the same type as the operands
  • 10. Francisco Ortín Soler Types of Typical Lambda Exprs • Notice: the methods of the interfaces must be explicitly called, and they are named differently (test, accept, apply, get…) public static void main(String... args) { MyPredicate<Integer> even = n -> n%2 == 0; // my own type Predicate<Integer> odd = n -> n%2 != 0; System.out.println(even.exec(number) + " " + odd.test(number)); Consumer<Integer> printAction = n -> System.out.println(n); printAction.accept(number); Function<Integer,Double> sqrt = n -> Math.sqrt(n); System.out.println(sqrt.apply(number)); Supplier<Integer> random = () -> (int)(Math.random()*1000 - 1000/2); System.out.println(random.get()); BinaryOperator<Integer> times = (a,b) -> a*b; System.out.printf(times.apply(3,2));
  • 11. Francisco Ortín Soler Types of Typical Lambda Exprs • Since generics is implemented in Java with type erasure (i.e., T is Object), the previous types have specific versions for built-in types: And more… http://download.java.net/jdk8/docs/api/java/util/function/package-summary.html Predicate<T> Supplier<T> Consumer<T> Function<T,R> DoublePredicate BooleanSupplier DoubleConsumer DoubleFunction<R> IntPredicate DoubleSupplier IntConsumer IntFunction<R> LongPredicate IntSupplier LongConsumer IntToDoubleFunction LongSupplier IntToLongFunction LongFunction<R> …
  • 12. Francisco Ortín Soler Streams with Aggregate Operations • The new java.util.stream package provides an API to support functional-style operations on streams • A stream is a sequence of elements  It is not a data structure that stores elements (i.e. a collection) • They support sequential and parallel functional-style aggregate operations • Operations are composed into a stream pipeline • Pipeline consists of  A source (array, collection, generator, I/O channel…)  Intermediate aggregate operations  And a terminal operation, producing a result • Computation on the source data is only performed when the terminal operation is initiated (kind of lazy)
  • 13. Francisco Ortín Soler Streams (Aggregate Operations) public class Streams { static int compute(Collection<Integer> collection) { return collection.stream() .filter(n -> n%2 == 0) // even numbers .map(n -> n*n) // square .reduce(0, (acc, item) -> acc + item); // summation } public static void main(String... args) { System.out.println(compute(Arrays.asList(1, 2, 3, 4, 5))); System.out.println(Arrays.asList( Stream.iterate(1, n -> n+1) .skip(10) .limit(5) .toArray(Integer[]::new) )); } } source aggregate operations terminal operation source (infinite) aggregate operations terminal operation • Similar to .NET LINQ • There will be database streams eventually?
  • 14. Francisco Ortín Soler Closures • Lambda expressions can capture variables of the enclosing scope • They do not have shadowing issues (a new scope is not created, being lexically scoped) • Captured variables must be final or effectively final (their value cannot be modified) public class Closures { static Function<Integer,Integer> createClosure(int initialValue) { int number = initialValue; // must be constant return n -> number + n; } public static void main(String... args) { Function<Integer,Integer> closure1 = createClosure(1); System.out.println(closure1.apply(7) ); Function<Integer,Integer> closure10 = createClosure(10); System.out.println(closure10.apply(7) ); } }
  • 15. Francisco Ortín Soler Closures • Since functions are objects, they can represent functions with a mutable state class Fibonacci implements Supplier<Integer> { private int previous = 0, current = 1; @Override public Integer get() { int next = current + previous; previous = current; current = next; return previous; } public static void main(String... args) { System.out.println(Arrays.asList( Stream.generate(new Fibonacci()).limit(10) .toArray(Integer[]::new) )); } }
  • 16. Francisco Ortín Soler Default Methods • Java 8 provides default implementations for interface methods (the default keyword is used), similar to mixins @FunctionalInterface interface Comparator<T> { int compare(T a, T b); default Comparator<T> reversed() { return (a, b) -> this.compare(b,a); } } public class DefaultMethods { public static <T> T max(T a, T b, Comparator<T> comp) { return comp.compare(a,b)<0 ? a : b; } public static <T> T min(T a, T b, Comparator<T> comp) { return max(a, b, comp.reversed()); } public static void main(String... args) { Comparator<String> comparator = (a,b) -> a.length() - b.length(); System.out.println(max("hello", "bye", comparator)); System.out.println(min("hello", "bye", comparator)); } }
  • 17. Francisco Ortín Soler Multiple Inheritance • As with multiple inheritance languages, different implementations of the same method may be inherited • However, the Java compiler checks this condition, reporting an error interface A { default void m() { System.out.println("A::m"); } } interface B { default void m() { System.out.println("B::m"); } } public class MultipleInheritance implements A, B { // compiler error }
  • 18. Francisco Ortín Soler Multiple Inheritance • Besides, a default method cannot be inherited if the class implements another interface with that method (even without a default implementation) interface A { default void m() { System.out.println("A::m"); } } interface C { void m(); } class MyClass implements A, C { // compiler error }
  • 19. Francisco Ortín Soler Multiple Inheritance • Java 8 allows diamond inheritance: the most specific (derived) method implementation is called interface A { default void m() { System.out.println("A::m"); } } interface A1 extends A {} interface A2 extends A { default void m() { System.out.println("A2::m"); } } class Diamond implements A1, A2 { public static void main(String... args) { new Diamond().m(); // A2::m A1 a1 = new Diamond(); a1.m(); } }
  • 20. Francisco Ortín Soler Static Methods • Java 8 allows interfaces to implement static methods to provide utility methods • The static methods specific to an interface can be kept in the same interface rather than in a separate class @FunctionalInterface interface Comparator<T> { int compare(T a, T b); static <T extends Comparable<T>> Comparator<T> naturalOrder() { return (a,b) -> a.compareTo(b); } } public class DefaultMethods { public static void main(String... args) { System.out.println( max("hello", "bye", Comparator.naturalOrder() )); } }
  • 21. Software Engineering Computer Science Engineering School Francisco Ortin University of Oviedo New Functional Features of Java 8