SlideShare a Scribd company logo
1 of 39
Download to read offline
FP in Java
               Project Lambda and beyond



by Mario Fusco
mario.fusco@gmail.com
twitter: @mariofusco
Project Lambda – A Brief History
•   2006 – Gosling: "We will never have closures in Java"
•   2007 – 3 different proposals for closures in Java
•   2008 – Reinhold: "We will never have closures in Java"
•   2009 – Start of project Lambda (JSR 335)


    public boolean javaWillHaveClosure() {
        return currentYear % 2 == 1;
    }
From Single Method Interfaces …
public interface Comparator<T> {              Functional
    int compare(T o1, T o2);
}                                             Interface
Collections.sort(strings, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
});

  Bulky syntax
  Confusion surrounding the meaning of names and this
  Inability to capture non-final local variables
  Inability to abstract over control flow
… To Lambda Expressions
Collections.sort(strings, (s1, s2) -> s1.compareToIgnoreCase(s2));


     Lambda expression are always converted to
         instance of a functional interface
Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase(s2);


                          Compiler figures out the types


    No need of changing the JVM to create a new
           type for lambda expressions
Anatomy of a lambda expression
 A lambda expression is like a method: it provides a list of formal parameters and a body

The formal parameters of
a lambda expression may
have either inferred or
                         s -> s.length()
declared types
                          (int x, int y) -> x + y

                          () -> 42                               Return is implicit and
                                                                 can be omitted
                          (x, y, z) -> {
                              if (x) {
                                  return y;                  A lambda body is either a
                              } else {                       single expression or a block
                                  return z;
                              }
                          }
Common JDK8 functional interfaces

Predicate     a property of the object passed as argument
Block      an action to be performed with the object passed as argument
Function      transform a T to a U
BiFunction      transform a (T, U) to a V
Supplier     provide an instance of a T (such as a factory)
UnaryOperator       a unary operator from T -> T
BinaryOperator       a binary operator from (T, T) -> T
Why Lambdas?
API designers can build more powerful, expressive APIs
More room for generalization
  o Pass behaviors to a method together with normal data
Libraries remain in control of computation
  o e.g. internal vs. external iteration
More opportunities for optimization
  o Laziness
  o Parallelism
  o Out-of-order execution
More regular and then more readable code
  o e.g. nested loops vs. pipelined (fluent) operations
Better composability and reusability
An Example: Sorting
Comparator<Person> byAge = new Comparator<Person>() {
    public int compare(Person p1, Person p2) {
        return p1.getAge() – p2.getAge();
                                                  Functional interface
    }
};

                                               Lambda expression
Collections.sort(people, byAge);



Comparator<Person> byAge = (p1, p2) -> p1.getAge() – p2.getAge();



Collections.sort(people, (p1, p2) -> p1.getAge() – p2.getAge());
Can We Do Better?
Comparator<Person> byAge = Comparators.comparing(p -> p.getAge());


Comparator<Person> byAge = Comparators.comparing(Person::getAge);

                                                     Method reference
       Readability
       Collections.sort(people, comparing(Person::getAge));


       Reusability
      Collections.sort(people, comparing(Person::getAge).reverse());


        Composability
       Collections.sort(people, comparing(Person::getAge)
                              .compose(comparing(Person::getName)));
Extension methods
 interface Iterator<E> {
     boolean hasNext();
     E next();
     void remove();

      default void forEach(Block<? super E> block) {
          while (hasNext())
              block.accept(next());
      }
 }

Add methods to existing interfaces without breaking the backward compatibility
Primary goal is API evolution, but useful as an inheritance mechanism on its own
Add multiple inheritance of behavior to the always existed multiple inheritance of
type, but no multiple inheritance of state
Extension methods
    interface Iterator<E> {
        boolean hasNext();
        E next();
default void remove(); { throw new UnsupportedOperationException(); }
             remove()

        default void forEach(Block<? super E> block) {
            while (hasNext())
                block.accept(next());
        }
   }

  Add methods to existing interfaces without breaking the backward compatibility
  Primary goal is API evolution, but useful as an inheritance mechanism on its own
  Add multiple inheritance of behavior to the always existed multiple inheritance of
  type, but no multiple inheritance of state
  Can be used to declare “optional” methods
Internal VS External iteration
  for (Employee e : employees) {
      e.setSalary(e.getSalary() * 1.03);
  }
                                            ̶ Inherently serial
                                             ̶ Client has to manage iteration
                                              ̶ Nested loops are poorly readable

    employees.forEach(e -> e.setSalary(e.getSalary() * 1.03));

                     Not only a syntactic change!
+ Library is in control   opportunity for internal optimizations as parallelization,
                          lazy evaluation, out-of-order execution
+ More what, less how better readability
+ Fluent (pipelined) operations better readability
+ Client can pass behaviors into the API as data
              possibility to abstract and generalize over behavior
                                                   more powerful, expressive APIs
Streams - Efficiency with laziness
employees.stream()
         .filter(e -> e.getIncome() > 50000)
         .map(e -> e.getName())
         .forEach(System.out::println);




   Represents a stream of values
   Not a data structure: doesn't store values
   Source can be Collection, array, generating function, I/O ....
   Encourages a pipelined ( "fluent" ) usage style
   Operations are divided between intermediate and terminal
   Lazy in nature: only terminal operations actually trigger a computation
Streams - Efficiency with laziness
           parallel()
employees.stream()
         .filter(e -> e.getIncome() > 50000)
         .map(e -> e.getName())
         .forEach(System.out::println);




   Represents a stream of values
   Not a data structure: doesn't store values
   Source can be Collection, array, generating function, I/O ....
   Encourages a pipelined ( "fluent" ) usage style
   Operations are divided between intermediate and terminal
   Lazy in nature: only terminal operations actually trigger a computation
   Also available a parallel stream (using the Fork/Join framework)
So we have lambdas in Java …




   … now what?
The OOP/FP dualism - OOP
public class Bird { }

public class Cat {
    private Bird catch;
    private boolean full;

    public void capture(Bird bird) {
        catch = bird;
                                       The story
    }

    public void eat() {
        full = true;
        catch = null;
    }
}

Cat cat = new Cat();
Bird bird = new Bird();

cat.capture(bird);
cat.eat();
The OOP/FP dualism - FP
public class Bird { }

public class Cat {
    public CatWithCatch capture(Bird bird) { return new CatWithCatch(bird); }
}

public class CatWithCatch {                                  Immutability
    private final Bird catch;
    public CatWithCatch(Bird bird) { catch = bird; }
    public FullCat eat() { return new FullCat(); }             Emphasis on verbs
}
                                                                instead of names
public class FullCat { }

BiFunction<Cat, Bird, FullCat> story =
        ((BiFunction<Cat, Bird, CatWithCatch>)Cat::capture)
                                              .compose(CatWithCatch::eat);

FullCat fullCat = story.apply( new Cat(), new Bird() );


        No need to test internal state: correctness enforced by the compiler
Better Logging with Lambdas
if (log.isDebugEnabled()) {
    log.debug("The answer is " + answer);
}
                           Invokes answer.toString() and does the Strings
                           concatenation even when not necessary


Can we delay the String creation and execute it only when
strictly necessary without (explicitly) using an if?

log.debug(()-> "The answer is " + answer);

public void debug(Callable<String> lambda) {
    if (isDebugEnabled()) {
        debug(lambda.call());
    }
}
Side-effect isolation                     Reusability
class Player {
    String name;   public void declareWinner(Player p) {
    int score;         System.out.println(p.name + " wins!");
}                  }
                   public void winner(Player p1, Player p2) {
                       if (p1.score > p2.score) declareWinner(p1)
                       else declareWinner(p2);
                   }
Side-effect isolation                     Reusability
class Player {
    String name;   public void declareWinner(Player p) {
    int score;         System.out.println(p.name + " wins!");
}                  }
                   public void winner(Player p1, Player p2) {
                       if (p1.score > p2.score) declareWinner(p1)
                       else declareWinner(p2);
                   }
                                                      Separate
                                                 computational logic
public Player maxScore(Player p1, Player p2) {    from side effects
    return p1.score > p2.score ? p1 : p2;
}
public void winner(Player p1, Player p2) {
    declareWinner(maxScore(p1, p2));
}
Side-effect isolation                     Reusability
class Player {
    String name;   public void declareWinner(Player p) {
    int score;         System.out.println(p.name + " wins!");
}                  }
                   public void winner(Player p1, Player p2) {
                       if (p1.score > p2.score) declareWinner(p1)
                       else declareWinner(p2);
                   }
                                                      Separate
                                                 computational logic
public Player maxScore(Player p1, Player p2) {    from side effects
    return p1.score > p2.score ? p1 : p2;
}
public void winner(Player p1, Player p2) {
    declareWinner(maxScore(p1, p2));
}
  declareWinner(players.stream().reduce(this::maxScore).get())

               reuse maxScore as a BinaryOperator
          to compute the winner among a list of players
Using Streams
public boolean isPrimeImperative(int number) {
    if (number < 2) {
        return false;
    }
    for (int i = 2; i < (int) Math.sqrt(number) + 1; i++) {
        if ( number % i == 0 ) {
           return false;
        }
    }
    return true;
}


public boolean isPrimeFunctional(int number) {
    return number > 1 &&
        Streams.intRange(2, (int) Math.sqrt(number) + 1)
               .noneMatch(divisor -> number % divisor == 0);
}
Working with infinite Streams
         take 25 (map (^2) [1..])




         (take 25 (squares-of (integers)))




         Stream.from(1).map(_ ^ 2).take(25).toArray




Stream<Integer> integers = Streams.iterate(1, i -> i + 1);
int[] result = integers.map(i -> i ^ 2).limit(25).toArray();
Null references? No, Thanks
Errors source NPE is by far the most common exception in Java
Bloatware source Worsen readability by making necessary to fill our
code with null checks
Meaningless Don't have any semantic meaning and in particular are the
wrong way to model the absence of a value in a statically typed language
Breaks Java philosophy Java always hides pointers to developers, except
in one case: the null pointer
A hole in the type system Null has the bottom type, meaning that it can
be assigned to any reference type: this is a problem because, when
propagated to another part of the system, you have no idea what that null
was initially supposed to be

  Tony Hoare, who invented the null reference in 1965 while working on
   an object oriented language called ALGOL W, called its invention his
                “billion dollar mistake”
Options: the functional alternative
public abstract class Option<A> implements Iterable<A> {
    private Option() { }

    public   abstract   <B> Option<B> map(Function<A, B> mapper);
    public   abstract   <B> Option<B> flatMap(Function<A, Option<B>> mapper);
    public   abstract   Option<A> filter(Predicate<A> predicate);
    public   abstract   A getOrElse(A def);
    public   abstract   boolean isDefined();

    public static <A> Some<A> some(A value) {
        if (value == null) throw new NullPointerException();
        return new Some<A>(value);
    }

    public static <A> None<A> none() { return None.NONE; }

    public static <A> Option<A> option(A value) {
        return value == null ? none() : some(value);
    }

    public static final class None<A> extends Option<A> { ... }
    public static final class Some<A> extends Option<A> { ... }
}
Some
public static final class Some<A> extends Option<A> {
    private final A value;
    private Some(A value) { this.value = value; }

    public <B> Option<B> map(Function<A, B> mapper) {
        return some( mapper.apply(value) );
    }

    public <B> Option<B> flatMap(Function<A, Option<B>> mapper) {
        return (Option<B>) mapper.apply(value);
    }

    public Option<A> filter(Predicate<? super A> predicate) {
        return predicate.test(value)) ? this : None.NONE;
    }

    public A getOrElse(A def) { return value; }
    public boolean isDefined() { return false; }
}
None
public static final class None<A> extends Option<A> {

    public static final None NONE = new None();

    private None() { }

    public <B> Option<B> map(Function<A, B> mapper) { return NONE; }

    public <B> Option<B> flatMap(Function<A, Option<B>> mapper) {
        return NONE;
    }

    public Option<A> filter(Predicate<A> predicate) { return NONE; }

    public A getOrElse(A def) { return def; }

    public boolean isDefined() { return false; }
}
Example: if the value associated with a given key
    is a String representing a positive integer returns
      that integer, but returns zero in all other case
@Test
public void testReturnPositiveIntegersOrZero() {
    Map<String, String> param = new HashMap<String, String>();
    param.put("a", "5");
    param.put("b", "true");
    param.put("c", "-3");

     // the value of   the key "a" is a String representing a
     // positive int   so return it
     assertEquals(5,   readPositiveIntParam(param, "a"));
     // returns zero   since the value of the key "b" is not an int
     assertEquals(0,   readPositiveIntParam(param, "b"));
     // returns zero   since the value of the key "c" is a negative int
     assertEquals(0,   readPositiveIntParam(param, "c"));
     // returns zero   since there is no key "d" in the map
     assertEquals(0,   readPositiveIntParam(param, "d"));
}
Null vs. Option
int readPositiveIntParam(Map<String, String> params, String name) {
    String value = params.get(name);
    if (value == null) return 0;
    int i = 0;
    try {
        i = Integer.parseInt(value);
     } catch (NumberFormatException e) { }
     return i < 0 ? 0 : i;
}


int readPositiveIntParam(Map<String, String> params, String name) {
    return asOption(params.get(name))
           .flatMap(s -> {
                    try { return some(Integer.parseInt(s)); }
                    catch (NumberFormatException e) { return none(); }
           })
           .filter(i -> i > 0)
           .getOrElse(0);
}
Exceptions? Yes, but …
Often abused, especially for flow control
Checked Exceptions harm API extensibility/modificability
Not composable: in presence of multiple errors only the first one is
reported
In the end just a GLORIFIED MULTILEVEL GOTO
Exceptions? Yes, but …
Often abused, especially for flow control
Checked Exceptions harm API extensibility/modificability
Not composable: in presence of multiple errors only the first one is
reported
In the end just a GLORIFIED MULTILEVEL GOTO


              Either/Validation:
          the functional alternative
The functional way of returning a value which can actually be one of two
values: the error/exception (Left) or the correct value (Right)



      Validation<Exception, Value>
Exceptions? Yes, but …
Often abused, especially for flow control
Checked Exceptions harm API extensibility/modificability
Not composable: in presence of multiple errors only the first one is
reported
In the end just a GLORIFIED MULTILEVEL GOTO


              Either/Validation:
          the functional alternative
The functional way of returning a value which can actually be one of two
values: the error/exception (Left) or the correct value (Right)
Composable: can accumulate multiple errors


 Validation<List<Exception>, Value>
   Validation<Exception, Value>
SalaryCalculator
public class SalaryCalculator {
    // B = basic + 20%
    public double plusAllowance(double d) { return d * 1.2; }

    // C = B + 10%
    public double plusBonus(double d) { return d * 1.1; }

    // D = C - 30%
    public double plusTax(double d) { return d * 0.7; }

    // E = D - 10%
    public double plusSurcharge(double d) { return d * 0.9; }

    public double calculate(double basic, boolean... bs) {
        double salary = basic;
        if (bs[0]) salary = plusAllowance(salary);
        if (bs[1]) salary = plusBonus(salary);
        if (bs[2]) salary = plusTax(salary);
        if (bs[3]) salary = plusSurcharge(salary);
        return salary;
    }
}
Endomorphisms & Monoids
    interface Endomorphism<A> extends Function<A, A> { }


    interface Monoid<A> {
        A append(A a1, A a2);
        A zero();
    }


interface EndoMonoid<A> extends Monoid<Endomorphism<A>> {
    @Override
    default Endomorphism<A> append(Endomorphism<A> a1, Endomorphism<A> a2) {
        return (A a) -> a2.apply(a1.apply(a));
    }

      @Override
      default Endomorphism<A> zero() {
          return a -> a;
      }
}
FluentEndoMonoid
public class FluentEndoMonoid<A> implements EndoMonoid<A> {
    private final Endomorphism<A> endo;

    public FluentEndoMonoid(Endomorphism<A> endo) { this.endo = endo; }
    public FluentEndoMonoid(Endomorphism<A> endo, boolean b) {
        this.endo = b ? endo : zero();
    }

    public FluentEndoMonoid<A> add(Endomorphism<A> other) {
        return new FluentEndoMonoid<A>(append(endo, other));
    }
    public FluentEndoMonoid<A> add(Endomorphism<A> other, boolean b) {
        return add(b ? other : zero());
    }

    public Endomorphism<A> get() { return endo; }

    public static <A> FluentEndoMonoid<A> endo(Endomorphism<A> f, boolean b) {
        return new FluentEndoMonoid<A>(f, b);
    }
}
Functional SalaryCalculator

public class SalaryCalculator {

    public double calculate(double basic, boolean... bs) {
        return endo((Endomorphism<Double>) this::plusAllowance, bs[0])
                .add(this::plusBonus, bs[1])
                .add(this::plusTax, bs[2])
                .add(this::plusSurcharge, bs[3])
                .get()
                .apply(basic);
    }
}
The bottom line


Java is getting functional

 EMBRACE IT!
References
Thanks … Questions?




Q                                                 A
Mario Fusco                          mario.fusco@gmail.com
Red Hat – Senior Software Engineer     twitter: @mariofusco

More Related Content

What's hot

Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programmingRiccardo Cardin
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART IOXUS 20
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORMSaurabh Dixit
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 

What's hot (20)

Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Hibernate
HibernateHibernate
Hibernate
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
React js
React jsReact js
React js
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
Log4 J
Log4 JLog4 J
Log4 J
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 

Viewers also liked

OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingMario Fusco
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Mario Fusco
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVMMario Fusco
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageMario Fusco
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep diveMario Fusco
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing DroolsMario Fusco
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 

Viewers also liked (17)

Hammurabi
HammurabiHammurabi
Hammurabi
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...Reactive Programming for a demanding world: building event-driven and respons...
Reactive Programming for a demanding world: building event-driven and respons...
 
Comparing different concurrency models on the JVM
Comparing different concurrency models on the JVMComparing different concurrency models on the JVM
Comparing different concurrency models on the JVM
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Drools 6 deep dive
Drools 6 deep diveDrools 6 deep dive
Drools 6 deep dive
 
Seven Deadly Sins
Seven Deadly Sins Seven Deadly Sins
Seven Deadly Sins
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Introducing Drools
Introducing DroolsIntroducing Drools
Introducing Drools
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 

Similar to FP in Java - Project Lambda and beyond

Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
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 presentation
Java 8 presentationJava 8 presentation
Java 8 presentationVan Huong
 
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
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazAlexey Remnev
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)Subhas Kumar Ghosh
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8Raffi Khatchadourian
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 

Similar to FP in Java - Project Lambda and beyond (20)

Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
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...
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
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
 
Java 8
Java 8Java 8
Java 8
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Thumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - JavazThumbtack Expertise Days # 5 - Javaz
Thumbtack Expertise Days # 5 - Javaz
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
C# programming
C# programming C# programming
C# programming
 
05 pig user defined functions (udfs)
05 pig user defined functions (udfs)05 pig user defined functions (udfs)
05 pig user defined functions (udfs)
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 

More from Mario Fusco

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automationMario Fusco
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...Mario Fusco
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 

More from Mario Fusco (6)

Kogito: cloud native business automation
Kogito: cloud native business automationKogito: cloud native business automation
Kogito: cloud native business automation
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Lazy java
Lazy javaLazy java
Lazy java
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 

Recently uploaded

9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 

Recently uploaded (20)

9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 

FP in Java - Project Lambda and beyond

  • 1. FP in Java Project Lambda and beyond by Mario Fusco mario.fusco@gmail.com twitter: @mariofusco
  • 2. Project Lambda – A Brief History • 2006 – Gosling: "We will never have closures in Java" • 2007 – 3 different proposals for closures in Java • 2008 – Reinhold: "We will never have closures in Java" • 2009 – Start of project Lambda (JSR 335) public boolean javaWillHaveClosure() { return currentYear % 2 == 1; }
  • 3. From Single Method Interfaces … public interface Comparator<T> { Functional int compare(T o1, T o2); } Interface Collections.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); Bulky syntax Confusion surrounding the meaning of names and this Inability to capture non-final local variables Inability to abstract over control flow
  • 4. … To Lambda Expressions Collections.sort(strings, (s1, s2) -> s1.compareToIgnoreCase(s2)); Lambda expression are always converted to instance of a functional interface Comparator<String> c = (s1, s2) -> s1.compareToIgnoreCase(s2); Compiler figures out the types No need of changing the JVM to create a new type for lambda expressions
  • 5. Anatomy of a lambda expression A lambda expression is like a method: it provides a list of formal parameters and a body The formal parameters of a lambda expression may have either inferred or s -> s.length() declared types (int x, int y) -> x + y () -> 42 Return is implicit and can be omitted (x, y, z) -> { if (x) { return y; A lambda body is either a } else { single expression or a block return z; } }
  • 6. Common JDK8 functional interfaces Predicate a property of the object passed as argument Block an action to be performed with the object passed as argument Function transform a T to a U BiFunction transform a (T, U) to a V Supplier provide an instance of a T (such as a factory) UnaryOperator a unary operator from T -> T BinaryOperator a binary operator from (T, T) -> T
  • 7. Why Lambdas? API designers can build more powerful, expressive APIs More room for generalization o Pass behaviors to a method together with normal data Libraries remain in control of computation o e.g. internal vs. external iteration More opportunities for optimization o Laziness o Parallelism o Out-of-order execution More regular and then more readable code o e.g. nested loops vs. pipelined (fluent) operations Better composability and reusability
  • 8. An Example: Sorting Comparator<Person> byAge = new Comparator<Person>() { public int compare(Person p1, Person p2) { return p1.getAge() – p2.getAge(); Functional interface } }; Lambda expression Collections.sort(people, byAge); Comparator<Person> byAge = (p1, p2) -> p1.getAge() – p2.getAge(); Collections.sort(people, (p1, p2) -> p1.getAge() – p2.getAge());
  • 9. Can We Do Better? Comparator<Person> byAge = Comparators.comparing(p -> p.getAge()); Comparator<Person> byAge = Comparators.comparing(Person::getAge); Method reference Readability Collections.sort(people, comparing(Person::getAge)); Reusability Collections.sort(people, comparing(Person::getAge).reverse()); Composability Collections.sort(people, comparing(Person::getAge) .compose(comparing(Person::getName)));
  • 10. Extension methods interface Iterator<E> { boolean hasNext(); E next(); void remove(); default void forEach(Block<? super E> block) { while (hasNext()) block.accept(next()); } } Add methods to existing interfaces without breaking the backward compatibility Primary goal is API evolution, but useful as an inheritance mechanism on its own Add multiple inheritance of behavior to the always existed multiple inheritance of type, but no multiple inheritance of state
  • 11. Extension methods interface Iterator<E> { boolean hasNext(); E next(); default void remove(); { throw new UnsupportedOperationException(); } remove() default void forEach(Block<? super E> block) { while (hasNext()) block.accept(next()); } } Add methods to existing interfaces without breaking the backward compatibility Primary goal is API evolution, but useful as an inheritance mechanism on its own Add multiple inheritance of behavior to the always existed multiple inheritance of type, but no multiple inheritance of state Can be used to declare “optional” methods
  • 12. Internal VS External iteration for (Employee e : employees) { e.setSalary(e.getSalary() * 1.03); } ̶ Inherently serial ̶ Client has to manage iteration ̶ Nested loops are poorly readable employees.forEach(e -> e.setSalary(e.getSalary() * 1.03)); Not only a syntactic change! + Library is in control opportunity for internal optimizations as parallelization, lazy evaluation, out-of-order execution + More what, less how better readability + Fluent (pipelined) operations better readability + Client can pass behaviors into the API as data possibility to abstract and generalize over behavior more powerful, expressive APIs
  • 13. Streams - Efficiency with laziness employees.stream() .filter(e -> e.getIncome() > 50000) .map(e -> e.getName()) .forEach(System.out::println); Represents a stream of values Not a data structure: doesn't store values Source can be Collection, array, generating function, I/O .... Encourages a pipelined ( "fluent" ) usage style Operations are divided between intermediate and terminal Lazy in nature: only terminal operations actually trigger a computation
  • 14. Streams - Efficiency with laziness parallel() employees.stream() .filter(e -> e.getIncome() > 50000) .map(e -> e.getName()) .forEach(System.out::println); Represents a stream of values Not a data structure: doesn't store values Source can be Collection, array, generating function, I/O .... Encourages a pipelined ( "fluent" ) usage style Operations are divided between intermediate and terminal Lazy in nature: only terminal operations actually trigger a computation Also available a parallel stream (using the Fork/Join framework)
  • 15. So we have lambdas in Java … … now what?
  • 16. The OOP/FP dualism - OOP public class Bird { } public class Cat { private Bird catch; private boolean full; public void capture(Bird bird) { catch = bird; The story } public void eat() { full = true; catch = null; } } Cat cat = new Cat(); Bird bird = new Bird(); cat.capture(bird); cat.eat();
  • 17. The OOP/FP dualism - FP public class Bird { } public class Cat { public CatWithCatch capture(Bird bird) { return new CatWithCatch(bird); } } public class CatWithCatch { Immutability private final Bird catch; public CatWithCatch(Bird bird) { catch = bird; } public FullCat eat() { return new FullCat(); } Emphasis on verbs } instead of names public class FullCat { } BiFunction<Cat, Bird, FullCat> story = ((BiFunction<Cat, Bird, CatWithCatch>)Cat::capture) .compose(CatWithCatch::eat); FullCat fullCat = story.apply( new Cat(), new Bird() ); No need to test internal state: correctness enforced by the compiler
  • 18. Better Logging with Lambdas if (log.isDebugEnabled()) { log.debug("The answer is " + answer); } Invokes answer.toString() and does the Strings concatenation even when not necessary Can we delay the String creation and execute it only when strictly necessary without (explicitly) using an if? log.debug(()-> "The answer is " + answer); public void debug(Callable<String> lambda) { if (isDebugEnabled()) { debug(lambda.call()); } }
  • 19. Side-effect isolation Reusability class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); }
  • 20. Side-effect isolation Reusability class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logic public Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2; } public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2)); }
  • 21. Side-effect isolation Reusability class Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!"); } } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logic public Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2; } public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2)); } declareWinner(players.stream().reduce(this::maxScore).get()) reuse maxScore as a BinaryOperator to compute the winner among a list of players
  • 22. Using Streams public boolean isPrimeImperative(int number) { if (number < 2) { return false; } for (int i = 2; i < (int) Math.sqrt(number) + 1; i++) { if ( number % i == 0 ) { return false; } } return true; } public boolean isPrimeFunctional(int number) { return number > 1 && Streams.intRange(2, (int) Math.sqrt(number) + 1) .noneMatch(divisor -> number % divisor == 0); }
  • 23. Working with infinite Streams take 25 (map (^2) [1..]) (take 25 (squares-of (integers))) Stream.from(1).map(_ ^ 2).take(25).toArray Stream<Integer> integers = Streams.iterate(1, i -> i + 1); int[] result = integers.map(i -> i ^ 2).limit(25).toArray();
  • 24. Null references? No, Thanks Errors source NPE is by far the most common exception in Java Bloatware source Worsen readability by making necessary to fill our code with null checks Meaningless Don't have any semantic meaning and in particular are the wrong way to model the absence of a value in a statically typed language Breaks Java philosophy Java always hides pointers to developers, except in one case: the null pointer A hole in the type system Null has the bottom type, meaning that it can be assigned to any reference type: this is a problem because, when propagated to another part of the system, you have no idea what that null was initially supposed to be Tony Hoare, who invented the null reference in 1965 while working on an object oriented language called ALGOL W, called its invention his “billion dollar mistake”
  • 25. Options: the functional alternative public abstract class Option<A> implements Iterable<A> { private Option() { } public abstract <B> Option<B> map(Function<A, B> mapper); public abstract <B> Option<B> flatMap(Function<A, Option<B>> mapper); public abstract Option<A> filter(Predicate<A> predicate); public abstract A getOrElse(A def); public abstract boolean isDefined(); public static <A> Some<A> some(A value) { if (value == null) throw new NullPointerException(); return new Some<A>(value); } public static <A> None<A> none() { return None.NONE; } public static <A> Option<A> option(A value) { return value == null ? none() : some(value); } public static final class None<A> extends Option<A> { ... } public static final class Some<A> extends Option<A> { ... } }
  • 26. Some public static final class Some<A> extends Option<A> { private final A value; private Some(A value) { this.value = value; } public <B> Option<B> map(Function<A, B> mapper) { return some( mapper.apply(value) ); } public <B> Option<B> flatMap(Function<A, Option<B>> mapper) { return (Option<B>) mapper.apply(value); } public Option<A> filter(Predicate<? super A> predicate) { return predicate.test(value)) ? this : None.NONE; } public A getOrElse(A def) { return value; } public boolean isDefined() { return false; } }
  • 27. None public static final class None<A> extends Option<A> { public static final None NONE = new None(); private None() { } public <B> Option<B> map(Function<A, B> mapper) { return NONE; } public <B> Option<B> flatMap(Function<A, Option<B>> mapper) { return NONE; } public Option<A> filter(Predicate<A> predicate) { return NONE; } public A getOrElse(A def) { return def; } public boolean isDefined() { return false; } }
  • 28. Example: if the value associated with a given key is a String representing a positive integer returns that integer, but returns zero in all other case @Test public void testReturnPositiveIntegersOrZero() { Map<String, String> param = new HashMap<String, String>(); param.put("a", "5"); param.put("b", "true"); param.put("c", "-3"); // the value of the key "a" is a String representing a // positive int so return it assertEquals(5, readPositiveIntParam(param, "a")); // returns zero since the value of the key "b" is not an int assertEquals(0, readPositiveIntParam(param, "b")); // returns zero since the value of the key "c" is a negative int assertEquals(0, readPositiveIntParam(param, "c")); // returns zero since there is no key "d" in the map assertEquals(0, readPositiveIntParam(param, "d")); }
  • 29. Null vs. Option int readPositiveIntParam(Map<String, String> params, String name) { String value = params.get(name); if (value == null) return 0; int i = 0; try { i = Integer.parseInt(value); } catch (NumberFormatException e) { } return i < 0 ? 0 : i; } int readPositiveIntParam(Map<String, String> params, String name) { return asOption(params.get(name)) .flatMap(s -> { try { return some(Integer.parseInt(s)); } catch (NumberFormatException e) { return none(); } }) .filter(i -> i > 0) .getOrElse(0); }
  • 30. Exceptions? Yes, but … Often abused, especially for flow control Checked Exceptions harm API extensibility/modificability Not composable: in presence of multiple errors only the first one is reported In the end just a GLORIFIED MULTILEVEL GOTO
  • 31. Exceptions? Yes, but … Often abused, especially for flow control Checked Exceptions harm API extensibility/modificability Not composable: in presence of multiple errors only the first one is reported In the end just a GLORIFIED MULTILEVEL GOTO Either/Validation: the functional alternative The functional way of returning a value which can actually be one of two values: the error/exception (Left) or the correct value (Right) Validation<Exception, Value>
  • 32. Exceptions? Yes, but … Often abused, especially for flow control Checked Exceptions harm API extensibility/modificability Not composable: in presence of multiple errors only the first one is reported In the end just a GLORIFIED MULTILEVEL GOTO Either/Validation: the functional alternative The functional way of returning a value which can actually be one of two values: the error/exception (Left) or the correct value (Right) Composable: can accumulate multiple errors Validation<List<Exception>, Value> Validation<Exception, Value>
  • 33. SalaryCalculator public class SalaryCalculator { // B = basic + 20% public double plusAllowance(double d) { return d * 1.2; } // C = B + 10% public double plusBonus(double d) { return d * 1.1; } // D = C - 30% public double plusTax(double d) { return d * 0.7; } // E = D - 10% public double plusSurcharge(double d) { return d * 0.9; } public double calculate(double basic, boolean... bs) { double salary = basic; if (bs[0]) salary = plusAllowance(salary); if (bs[1]) salary = plusBonus(salary); if (bs[2]) salary = plusTax(salary); if (bs[3]) salary = plusSurcharge(salary); return salary; } }
  • 34. Endomorphisms & Monoids interface Endomorphism<A> extends Function<A, A> { } interface Monoid<A> { A append(A a1, A a2); A zero(); } interface EndoMonoid<A> extends Monoid<Endomorphism<A>> { @Override default Endomorphism<A> append(Endomorphism<A> a1, Endomorphism<A> a2) { return (A a) -> a2.apply(a1.apply(a)); } @Override default Endomorphism<A> zero() { return a -> a; } }
  • 35. FluentEndoMonoid public class FluentEndoMonoid<A> implements EndoMonoid<A> { private final Endomorphism<A> endo; public FluentEndoMonoid(Endomorphism<A> endo) { this.endo = endo; } public FluentEndoMonoid(Endomorphism<A> endo, boolean b) { this.endo = b ? endo : zero(); } public FluentEndoMonoid<A> add(Endomorphism<A> other) { return new FluentEndoMonoid<A>(append(endo, other)); } public FluentEndoMonoid<A> add(Endomorphism<A> other, boolean b) { return add(b ? other : zero()); } public Endomorphism<A> get() { return endo; } public static <A> FluentEndoMonoid<A> endo(Endomorphism<A> f, boolean b) { return new FluentEndoMonoid<A>(f, b); } }
  • 36. Functional SalaryCalculator public class SalaryCalculator { public double calculate(double basic, boolean... bs) { return endo((Endomorphism<Double>) this::plusAllowance, bs[0]) .add(this::plusBonus, bs[1]) .add(this::plusTax, bs[2]) .add(this::plusSurcharge, bs[3]) .get() .apply(basic); } }
  • 37. The bottom line Java is getting functional EMBRACE IT!
  • 39. Thanks … Questions? Q A Mario Fusco mario.fusco@gmail.com Red Hat – Senior Software Engineer twitter: @mariofusco