SlideShare uma empresa Scribd logo
1 de 65
Baixar para ler offline
Improve Your Java Code, Functional-Style - Now!


                                        John	
  Ferguson	
  Smart
                                 john.smart@wakaleo.com
                                 	
  h2p://www.wakaleo.com
                                            Twi2er:	
  wakaleo
So who is this guy, anyway?
               Consulta
                       nt
               Trainer
              Mentor
              Author
             Speaker
             Coder
   John Fer
            guson S
                    mar t
f(x,y) = x + y

Func:onal	
  Programming	
  is	
  the	
  new	
  black
Immutability	
  is	
  your	
  friend
Avoid	
  nasty	
  side-­‐effects
Benefit	
  from	
  concurrency
No	
  more	
  messy	
  loops
How
What
Func:onal	
  Programming	
  in	
  Java




 Coming	
  to	
  a	
  JVM	
  near	
  you	
  the	
  summer	
  of	
  2013
Java	
  8	
  supports	
  Lambda	
  Expressions


List<String> names
    = Arrays.asList("Aristotle", "Plato", "Socrates", "Pythagoras");

List<String> filteredNames = names
       .filter(name -> name.startsWith("P"))
       .into(new ArrayList<String>());

assertThat(filteredNames, contains("Plato", "Pythagoras"));
Java	
  8	
  supports	
  Lambda	
  Expressions
["Aristotle", "Plato", "Socrates", "Pythagoras"]




  names.filter(name -> name.startsWith("P"))
       .into(new ArrayList<String>());




             ["Plato", "Pythagoras"]
Java	
  8	
  supports	
  Lambda	
  Expressions
public class Pet {
    private String name;
    private Species species;

    Pet(String name, Species species) {...}

    public String getName() {...}
    public Species getSpecies() {...}

    @Override
    public boolean equals(Object o) {...}

    @Override
    public int hashCode() {...}

    enum Species {
        Cat,
        Dog,
        GuineaPig;
        Pet called(String name) { return new Pet(name, this); }
    }
}
Java	
  8	
  supports	
  Lambda	
  Expressions
          public class Pet {
List<Pet>     private String name;
           pets = Arrays.asList(Cat.called("Ginger"),
              private Species species;
                               Dog.called("Spot"),
                               GuineaPig.called("Fluffy"),
             Pet(String name, Species species) {...}
                               Dog.called("Rover"));
              public String getName() {...}
List<Pet>     public Species getSpecies()-> a.getSpecies() == Dog)
           sortedDogs = pets.filter(a {...}
                           .sorted((a, b) -> a.getName().compareTo(b.getName()))
                           .into(new ArrayList<Pet>());
             @Override
             public boolean equals(Object o) {...}
assertThat(sortedDogs, contains(Dog.called("Rover"),
             @Override          Dog.called("Spot")));
             public int hashCode() {...}

             enum Species {
                 Cat,
                 Dog,
                 GuineaPig;
                 Pet called(String name) { return new Pet(name, this); }
             }
         }
Java	
  8	
  supports	
  Lambda	
  Expressions
          [Ginger, Spot, Fluffy, Rover]




pets.filter(a -> a.getSpecies() == Dog)
    .sorted((a, b) -> a.getName().compareTo(b.getName()))
    .into(new ArrayList<Pet>());




                     [Rover, Spot]
Java	
  8	
  supports	
  Lambda	
  Expressions
          [Ginger, Spot, Fluffy, Rover]




pets.filter(a -> a.getSpecies() == Dog)
    .map(e -> { return e.getName(); })
    .sorted((a, b) -> a.compareTo(b))
    .into(new ArrayList<Pet>());




                  ["Rover", "Spot"]
Java	
  8	
  supports	
  Lambda	
  Expressions
                    [Ginger, Spot, Fluffy, Rover]




Predicate<Pet> carnivores = (pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat);

List<Pet> carnivorousPets = pets.filter(carnivores).into(new ArrayList<Pet>());




                   ["Ginger", "Spot", "Rover"]
Java	
  8	
  supports	
  Lambda	
  Expressions
                  [Ginger, Spot, Fluffy, Rover]




pets.filter((pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat))
    .into(new ArrayList<Pet>());




                 ["Ginger", "Spot", "Rover"]
Java	
  8	
  supports	
  Lambda	
  Expressions
public class VetStay {
    private Pet pet;
    private Date startOfStay;
    private String diagnosis;

    public VetStay(Pet pet, Date startOfStay, String diagnosis) {
        this.pet = pet;
        this.startOfStay = startOfStay;
        this.diagnosis = diagnosis;
    }
}



   List<VetStay> vetStays = pets.map(pet -> {
                                       return new VetStay(pet, new Date(), "sore paw");})
                                .into(new ArrayList<VetStay>());
Java	
  8	
  supports	
  Lambda	
  Expressions


List<Pet> pets = Arrays.asList(Cat.called("Ginger"),
        Dog.called("Spot"),
        GuineaPig.called("Fluffy"),
        Dog.called("Rover")
);

assert pets.anyMatch(pet -> pet.getSpecies() == Dog)
But	
  Func:onal	
  Programming	
  in	
  Java	
  today?




Surely	
  this	
  is	
  madness!
Google Guava
Immutable	
  Collec:ons

Defensive
Thread-safe
Efficient
Immutable	
  Collec:ons

                                      Creating an immutable list

List<String> colors = ImmutableList.of("red", "green", "blue");

    Set<String> colors = ImmutableSet. of("red", "green", "blue");
    Set<String> myColors = ImmutableSet.copyOf(colors);


                                  Creating an immutable copy
No	
  more	
  returning	
  Null

“Null sucks.”
                                          - Doug Lea


“I call it my billion-dollar mistake.”
                                     - Sir Tony Hoare
No	
  more	
  returning	
  Null
                        What does a null return value mean?

interface ClientService {
    Client findByName(String name);
}


 No matching client found (but we were expecting one)?

     No matching client found (but we’re cool with that)?

       Something went wrong?
No	
  more	
  returning	
  Null
                         Sometimes we might not return a client

        interface ClientService {
            Optional<Client> findByName(String name);
        }


                     This forces us to cater for this case in our code


Optional<Client> clientOptional = clientService.findByName("Smith");
if (clientOptional.isPresent()) {
    Client client = clientOptional.get();
} else {
    // No client was found
}
No	
  more	
  returning	
  Null

                      A person may not have a favorite color
  class Person {
      Optional<Color> getFavoriteColor();
  }


Color colorToUse = person.getFavoriteColor().or(Blue)



                                      If not, use Blue
And	
  lots	
  of	
  other	
  stuff...
No	
  more	
  returning	
  Null
                        What does a null return value mean?

interface ClientService {
    Client findByName(String name);
}


 No matching client found (but we were expecting one)?

     No matching client found (but we’re cool with that)?

       Something went wrong?
No	
  more	
  returning	
  Null
                         Sometimes we might not return a client

        interface ClientService {
            Optional<Client> findByName(String name);
        }


                     This forces us to cater for this case in our code


Optional<Client> clientOptional = clientService.findByName("Smith");
if (clientOptional.isPresent()) {
    Client client = clientOptional.get();
} else {
    // No client was found
}
No	
  more	
  returning	
  Null

                      A person may not have a favorite color
  class Person {
      Optional<Color> getFavoriteColor();
  }


Color colorToUse = person.getFavoriteColor().or(Blue)



                                      If not, use Blue
lambdaj
– DSL for manipulating collections in a functional style
– Replace loops with more concise and readable code
LambdaJ support many high level
collection-related functions


 filter                 aggregate


          sort
                      convert

extract                      group
Filtering	
  in	
  LambdaJ

import static ch.lambdaj.Lambda.filter;
import static org.hamcrest.Matchers.startsWith;
.
.
.
List<String> names
    = Arrays.asList("Aristotle", "Plato", "Socrates", "Pythagoras");

List<String> filteredNames = filter(startsWith("P"), names);

assertThat(filteredNames, contains("Plato", "Pythagoras"));




                    LambdaJ

                                 Hamcrest
Filtering	
  in	
  LambdaJ
["Aristotle", "Plato", "Socrates", "Pythagoras"]




        filter(startsWith("P"), names)




            ["Plato", "Pythagoras"]
Filtering	
  in	
  LambdaJ
List<String> filteredNames = new ArrayList<>();
for(String name : names) {
    if (name.startsWith("P")) {
        filteredNames.add(name);
    }
}
                                            Old-style Java


  names.filter(name -> name.startsWith("P"))
       .into(new ArrayList<String>());
                                        Java 8



         filter(startsWith("P"), names)
                                    Lambda J
Filtering	
  in	
  LambdaJ

List<Pet> pets = Arrays.asList(Cat.called("Ginger"),
                               Dog.called("Spot"),
                               GuineaPig.called("Fluffy"),
                               Dog.called("Rover"));

List<Pet> sortedDogs = filter(having(on(Pet.class).getSpecies(),
                                     is(Dog)), pets);

assertThat(sortedDogs, contains(Dog.called("Rover"), Dog.called("Spot")));
Filtering	
  in	
  LambdaJ
             [Ginger, Spot, Fluffy, Rover]




filter(having(on(Pet.class).getSpecies(), is(Dog)), pets);




                      [Rover, Spot]
Sor:ng	
  in	
  LambdaJ
      [Ginger, Spot, Fluffy, Rover]




sort(sortedDogs, on(Pet.class).getName());




      [Fluffy, Ginger, Rover, Spot]
Filtering	
  and	
  Sor:ng	
  in	
  LambdaJ
                [Ginger, Spot, Fluffy, Rover]




List<Pet> filteredDogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets);
List<Pet> sortedDogs = sort(filteredDogs, on(Pet.class).getName());




                              [Rover, Spot]
Extrac:ng	
  in	
  LambdaJ
          [Ginger, Spot, Fluffy, Rover]




pets.filter(a -> a.getSpecies() == Dog)
    .map(e -> { return e.getName(); })
    .sorted((a, b) -> a.compareTo(b))
    .into(new ArrayList<Pet>());
                                          Extracting with Java 8




                  ["Rover", "Spot"]
Extrac:ng	
  in	
  LambdaJ
                 [Ginger, Spot, Fluffy, Rover]




List<Pet> dogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets);
List<String> dogNames = extract(dogs, on(Pet.class).getName());
List<String> sortedDogNames = sort(dogNames,on(String.class));


                                                     Extracting with
                                                       LambdaJ


                         ["Rover", "Spot"]
Extrac:ng	
  in	
  LambdaJ
            [Ginger, Spot, Fluffy, Rover]
List<Pet> filteredDogs = new ArrayList();
for(Pet pet : pets) {
    if (pet.getSpecies() == Dog) {
        filteredDogs.add(pet);
    }
}
Collections.sort(filteredDogs, new Comparator<Pet>() {
    @Override
    public int compare(Pet pet, Pet pet1) {
        return pet.getName().compareTo(pet1.getName());
    }
});

                                     Extracting with old-style
                    ["Rover", "Spot"]          Java
Extrac:ng	
  in	
  LambdaJ
                 [Ginger, Spot, Fluffy, Rover]




List<Pet> dogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets);
List<String> dogNames = extract(dogs, on(Pet.class).getName());
List<String> sortedDogNames = sort(dogNames,on(String.class));


                                                     Extracting with
                                                       LambdaJ


                         ["Rover", "Spot"]
Conver:ng	
  in	
  LambdaJ

List<VetStay> vetStays = pets.map(pet -> {
         return new VetStay(pet, new Date(), "sore paw");})
                             .into(new ArrayList<VetStay>());

                                                                Converting with Java 8


   convert(pets, toVetStay());

      private Converter<Pet, VetStay> toVetStay() {
          return new Converter<Pet, VetStay>() {
              @Override
              public VetStay convert(Pet pet) {
                  return new VetStay(pet, new Date(), "sore paw");
              }
          };
      }
                                                        Converting with LambdaJ
Grouping	
  in	
  LambdaJ
       [Ginger, Spot, Fluffy, Rover]




Group<Pet> petsBySpecies = group(pets,
by(on(Pet.class).getSpecies()));

List<Pet> dogs = petsBySpecies.find(Dog);




                   [Spot,Rover]
FlaOening	
  in	
  LambdaJ
    [[Spot, Rover], [Ginger], [Fluffy]]




List<List<Pet>> petsBySpecies = ...

List<Pet> allPets = flatten(petsBySpecies);




        [Spot, Rover, Ginger, Fluffy]
Checking	
  existence	
  in	
  LambdaJ
         [Spot, Rover, Ginger, Fluffy]




exists(pets, having(on(Pet.class).getSpecies(), is(Cat)))




                         true
Using	
  Predicates	
  in	
  LambdaJ

Predicate<Pet> carnivores = (pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat);

List<Pet> carnivorousPets = pets.filter(carnivores).into(new ArrayList<Pet>());

                                                                                  Java 8

Matcher<Pet> carnivore = new Predicate<Pet>() {
    public boolean apply(Pet pet) {
        return (pet.getSpecies() == Dog || pet.getSpecies() == Cat);
    }
};

List<Pet> carnivores = filter(carnivore, pets);
                                                                              LambdaJ
Using	
  Aggregates	
  in	
  LambdaJ

List<Pet> pets = Arrays.asList(Cat.called("Ginger"),
        Dog.called("Spot"),
        GuineaPig.called("Fluffy"),
        Dog.called("Rover")
);

int ageOfOldestPet = maxFrom(pets).getAge();
int ageOfYoungestPet = minFrom(pets).getAge();
int totalPetAges = sumFrom(pets).getAge();
Some	
  real-­‐world	
  examples
TestOutcome	
  1
  SUCCESS TestOutcome	
  2
              SUCCESS        TestOutcome	
  3
                                                TestOutcome	
  4
                               FAILURE
                                                  PENDING




                TestOutcome	
  1
                  SUCCESS TestOutcome	
  2
                                  SUCCESS
Some	
  real-­‐world	
  examples
             TestOutcome	
  1
               SUCCESS TestOutcome	
  2
                           SUCCESS        TestOutcome	
  3
                                                             TestOutcome	
  4
                                            FAILURE
                                                               PENDING




filter(having(on(TestOutcome.class).getResult(), is(SUCCESS)), outcomes);




                             TestOutcome	
  1
                               SUCCESS TestOutcome	
  2
                                               SUCCESS
Some	
  real-­‐world	
  examples
            TestOutcome	
  1
              SUCCESS TestOutcome	
  2
                          SUCCESS        TestOutcome	
  3
                                                            TestOutcome	
  4
                                           FAILURE
                                                              PENDING




                    filter(withResult(SUCCESS)), outcomes);

private Matcher<?> withResult(TestResult expectedResult) {
    return having(on(TestOutcome.class).getResult(), is(expectedResult));
}

                            TestOutcome	
  1
                              SUCCESS TestOutcome	
  2
                                              SUCCESS
Some	
  real-­‐world	
  examples
         TestOutcome	
  1
           SUCCESS TestOutcome	
  2
                       SUCCESS        TestOutcome	
  3
                                                         TestOutcome	
  4
                                        FAILURE
                                                           PENDING




filter(anyOf(withResult(SUCCESS), withResult(PENDING)), outcomes);




                         TestOutcome	
  1
                           SUCCESSTestOutcome	
  2
                                    SUCCESSTestOutcome	
  4
                                             PENDING
Some	
  real-­‐world	
  examples
TestOutcome	
  1
  SUCCESS TestOutcome	
  2
                      SUCCESS           TestOutcome	
  3
                                                           TestOutcome	
  4
                                          FAILURE
                                                             PENDING


                              TestOutcome	
  2
      Step	
  1
         Step	
  2
           Step	
  3
                  Step	
  4
Some	
  real-­‐world	
  examples

                                            Tag
                                            Tag 1
             TagProvider1                     Tag


               TagProvider2                   Tag
                                               Tag
                                                Tag
                                                 Tag



flatten(extract(TagProviders, on(TagProvider.class).getTags()));




                              Tag
                              Tag 1
                                Tag
                                Tag
                                 Tag
                                  Tag
                                   Tag
And	
  performance	
  in	
  all	
  that?
Keeping	
  things	
  maintainable




“Excessive use of Guava's functional programming idioms can
lead to verbose, confusing, unreadable, and inefficient code.”
                                              - the Guava team

                                Can also be true of LambdaJ
Keeping	
  things	
  maintainable




                          RULE 1

Use a functional style when it makes the intent more readable
Keeping	
  things	
  maintainable



sort(extract(filter(having(on(Pet.class).getSpecies(), is(Dog)), pets),
  on(Pet.class).getName()), on(String.class));




List<Pet> dogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets);
List<String> dogNames = extract(dogs, on(Pet.class).getName());
List<String> sortedDogNames = sort(dogNames, on(String.class));
Keeping	
  things	
  maintainable




              RULE 2

   One-liners are not always better
Keeping	
  things	
  maintainable

convert(pets,
        new Converter<Pet, VetStay>() {
                    @Override
                    public VetStay convert(Pet pet) {
                        return new VetStay(pet, new Date(), "sore paw");
                    }
        }
);


convert(pets, toVetStay());
private Converter<Pet, VetStay> toVetStay() {
    return new Converter<Pet, VetStay>() {
        @Override
        public VetStay convert(Pet pet) {
            return new VetStay(pet, new Date(), "sore paw");
        }
    };
}
Keeping	
  things	
  maintainable




               RULE 3

Write your own domain-specific matchers
Keeping	
  things	
  maintainable


private Matcher<?> withResult(TestResult expectedResult) {
    return having(on(TestOutcome.class).getResult(), is(expectedResult));
}


   filter(withResult(SUCCESS)), outcomes);

     select(not(withResult(SUCCESS))), outcomes);

       select(anyOf(withResult(SKIPPED), withResult(IGNORED)), outcomes);
Thank You



       John	
  Ferguson	
  Smart
john.smart@wakaleo.com
	
  h2p://www.wakaleo.com
           Twi2er:	
  wakaleo

Mais conteúdo relacionado

Mais procurados

Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to knowTomasz Dziurko
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsCodeOps Technologies LLP
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116Paulo Morgado
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJosé Paumard
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserYodalee
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaMite Mitreski
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidJordi Gerona
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Paulo Morgado
 

Mais procurados (20)

Google guava
Google guavaGoogle guava
Google guava
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Kpi driven-java-development-fn conf
Kpi driven-java-development-fn confKpi driven-java-development-fn conf
Kpi driven-java-development-fn conf
 

Destaque

Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete Adnan abid
 
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
Ch4 Algorthmique Avancée - Analyse & complexité des AlgorithmesCh4 Algorthmique Avancée - Analyse & complexité des Algorithmes
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmeslotfibenromdhane
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJosé Paumard
 
Ch3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes RécursivesCh3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes Récursiveslotfibenromdhane
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Ch7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-CopmlétudeCh7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-Copmlétudelotfibenromdhane
 
Ch5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de TriCh5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de Trilotfibenromdhane
 
Ch2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - RécursivitéCh2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - Récursivitélotfibenromdhane
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Ch1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de BaseCh1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de Baselotfibenromdhane
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJosé Paumard
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJosé Paumard
 
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm
 
Alphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server FacesAlphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server FacesAlphorm
 
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm
 

Destaque (20)

Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
 
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
Ch4 Algorthmique Avancée - Analyse & complexité des AlgorithmesCh4 Algorthmique Avancée - Analyse & complexité des Algorithmes
Ch4 Algorthmique Avancée - Analyse & complexité des Algorithmes
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Ch3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes RécursivesCh3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes Récursives
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Cats
CatsCats
Cats
 
Functional Programming in JAVA 8
Functional Programming in JAVA 8Functional Programming in JAVA 8
Functional Programming in JAVA 8
 
Ch7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-CopmlétudeCh7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-Copmlétude
 
Notifications
NotificationsNotifications
Notifications
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Ch5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de TriCh5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de Tri
 
Ch2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - RécursivitéCh2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - Récursivité
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Ch1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de BaseCh1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de Base
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne Tour
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
 
Alphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server FacesAlphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server Faces
 
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certification
 

Semelhante a Functional programming in java

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Grails - The search is over
Grails - The search is overGrails - The search is over
Grails - The search is overFelipe Coutinho
 
FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101Faisal Abid
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. ExperienceMike Fogus
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...James Titcumb
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrowPete McFarlane
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 

Semelhante a Functional programming in java (20)

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Scala
ScalaScala
Scala
 
Grails - The search is over
Grails - The search is overGrails - The search is over
Grails - The search is over
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

Mais de John Ferguson Smart Limited

My Reading Specs - Refactoring Patterns for Gherkin Scenarios
My Reading Specs - Refactoring Patterns for Gherkin ScenariosMy Reading Specs - Refactoring Patterns for Gherkin Scenarios
My Reading Specs - Refactoring Patterns for Gherkin ScenariosJohn Ferguson Smart Limited
 
Artisti e Condotierri - How can your team become artists of the 21st century ...
Artisti e Condotierri - How can your team become artists of the 21st century ...Artisti e Condotierri - How can your team become artists of the 21st century ...
Artisti e Condotierri - How can your team become artists of the 21st century ...John Ferguson Smart Limited
 
Engage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a differenceEngage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a differenceJohn Ferguson Smart Limited
 
Sustainable Test Automation with Serenity BDD and Screenplay
Sustainable Test Automation with Serenity BDD and ScreenplaySustainable Test Automation with Serenity BDD and Screenplay
Sustainable Test Automation with Serenity BDD and ScreenplayJohn Ferguson Smart Limited
 
Engage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a differenceEngage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a differenceJohn Ferguson Smart Limited
 
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...John Ferguson Smart Limited
 
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...John Ferguson Smart Limited
 
Screenplay - Next generation automated acceptance testing
Screenplay - Next generation automated acceptance testingScreenplay - Next generation automated acceptance testing
Screenplay - Next generation automated acceptance testingJohn Ferguson Smart Limited
 
All the world's a stage – the next step in automated testing practices
All the world's a stage – the next step in automated testing practicesAll the world's a stage – the next step in automated testing practices
All the world's a stage – the next step in automated testing practicesJohn Ferguson Smart Limited
 
It's Testing, Jim, but not as we know it - BDD for Testers
It's Testing, Jim, but not as we know it - BDD for TestersIt's Testing, Jim, but not as we know it - BDD for Testers
It's Testing, Jim, but not as we know it - BDD for TestersJohn Ferguson Smart Limited
 

Mais de John Ferguson Smart Limited (20)

My Reading Specs - Refactoring Patterns for Gherkin Scenarios
My Reading Specs - Refactoring Patterns for Gherkin ScenariosMy Reading Specs - Refactoring Patterns for Gherkin Scenarios
My Reading Specs - Refactoring Patterns for Gherkin Scenarios
 
Artisti e Condotierri - How can your team become artists of the 21st century ...
Artisti e Condotierri - How can your team become artists of the 21st century ...Artisti e Condotierri - How can your team become artists of the 21st century ...
Artisti e Condotierri - How can your team become artists of the 21st century ...
 
Engage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a differenceEngage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a difference
 
BE A POD OF DOLPHINS, NOT A DANCING ELEPHANT
BE A POD OF DOLPHINS, NOT A DANCING ELEPHANTBE A POD OF DOLPHINS, NOT A DANCING ELEPHANT
BE A POD OF DOLPHINS, NOT A DANCING ELEPHANT
 
Sustainable Test Automation with Serenity BDD and Screenplay
Sustainable Test Automation with Serenity BDD and ScreenplaySustainable Test Automation with Serenity BDD and Screenplay
Sustainable Test Automation with Serenity BDD and Screenplay
 
Feature Mapping Workshop
Feature Mapping WorkshopFeature Mapping Workshop
Feature Mapping Workshop
 
Engage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a differenceEngage! Bringing teams together to deliver software that makes a difference
Engage! Bringing teams together to deliver software that makes a difference
 
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
 
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
Beyond Given/When/Then - why diving into Cucumber is the wrong approach to ad...
 
Shift left-devoxx-pl
Shift left-devoxx-plShift left-devoxx-pl
Shift left-devoxx-pl
 
Screenplay - Next generation automated acceptance testing
Screenplay - Next generation automated acceptance testingScreenplay - Next generation automated acceptance testing
Screenplay - Next generation automated acceptance testing
 
Cucumber and Spock Primer
Cucumber and Spock PrimerCucumber and Spock Primer
Cucumber and Spock Primer
 
All the world's a stage – the next step in automated testing practices
All the world's a stage – the next step in automated testing practicesAll the world's a stage – the next step in automated testing practices
All the world's a stage – the next step in automated testing practices
 
CukeUp 2016 Agile Product Planning Workshop
CukeUp 2016 Agile Product Planning WorkshopCukeUp 2016 Agile Product Planning Workshop
CukeUp 2016 Agile Product Planning Workshop
 
BDD Anti-patterns
BDD Anti-patternsBDD Anti-patterns
BDD Anti-patterns
 
Serenity and the Journey Pattern
Serenity and the Journey PatternSerenity and the Journey Pattern
Serenity and the Journey Pattern
 
BDD - Collaborate like you mean it!
BDD - Collaborate like you mean it!BDD - Collaborate like you mean it!
BDD - Collaborate like you mean it!
 
BDD-Driven Microservices
BDD-Driven MicroservicesBDD-Driven Microservices
BDD-Driven Microservices
 
BDD Anti-patterns
BDD Anti-patternsBDD Anti-patterns
BDD Anti-patterns
 
It's Testing, Jim, but not as we know it - BDD for Testers
It's Testing, Jim, but not as we know it - BDD for TestersIt's Testing, Jim, but not as we know it - BDD for Testers
It's Testing, Jim, but not as we know it - BDD for Testers
 

Functional programming in java

  • 1. Improve Your Java Code, Functional-Style - Now! John  Ferguson  Smart john.smart@wakaleo.com  h2p://www.wakaleo.com Twi2er:  wakaleo
  • 2. So who is this guy, anyway? Consulta nt Trainer Mentor Author Speaker Coder John Fer guson S mar t
  • 3. f(x,y) = x + y Func:onal  Programming  is  the  new  black
  • 9. Func:onal  Programming  in  Java Coming  to  a  JVM  near  you  the  summer  of  2013
  • 10. Java  8  supports  Lambda  Expressions List<String> names = Arrays.asList("Aristotle", "Plato", "Socrates", "Pythagoras"); List<String> filteredNames = names        .filter(name -> name.startsWith("P"))        .into(new ArrayList<String>()); assertThat(filteredNames, contains("Plato", "Pythagoras"));
  • 11. Java  8  supports  Lambda  Expressions ["Aristotle", "Plato", "Socrates", "Pythagoras"] names.filter(name -> name.startsWith("P"))      .into(new ArrayList<String>()); ["Plato", "Pythagoras"]
  • 12. Java  8  supports  Lambda  Expressions public class Pet {     private String name;     private Species species;     Pet(String name, Species species) {...}     public String getName() {...}     public Species getSpecies() {...}     @Override     public boolean equals(Object o) {...}     @Override     public int hashCode() {...}     enum Species {         Cat,         Dog,         GuineaPig;         Pet called(String name) { return new Pet(name, this); }     } }
  • 13. Java  8  supports  Lambda  Expressions public class Pet { List<Pet>     private String name; pets = Arrays.asList(Cat.called("Ginger"),     private Species species;                                Dog.called("Spot"),                                GuineaPig.called("Fluffy"),     Pet(String name, Species species) {...}                                Dog.called("Rover"));     public String getName() {...} List<Pet>     public Species getSpecies()-> a.getSpecies() == Dog) sortedDogs = pets.filter(a {...}                            .sorted((a, b) -> a.getName().compareTo(b.getName()))                            .into(new ArrayList<Pet>());     @Override     public boolean equals(Object o) {...} assertThat(sortedDogs, contains(Dog.called("Rover"),              @Override Dog.called("Spot")));     public int hashCode() {...}     enum Species {         Cat,         Dog,         GuineaPig;         Pet called(String name) { return new Pet(name, this); }     } }
  • 14. Java  8  supports  Lambda  Expressions [Ginger, Spot, Fluffy, Rover] pets.filter(a -> a.getSpecies() == Dog)     .sorted((a, b) -> a.getName().compareTo(b.getName()))     .into(new ArrayList<Pet>()); [Rover, Spot]
  • 15. Java  8  supports  Lambda  Expressions [Ginger, Spot, Fluffy, Rover] pets.filter(a -> a.getSpecies() == Dog) .map(e -> { return e.getName(); }) .sorted((a, b) -> a.compareTo(b))     .into(new ArrayList<Pet>()); ["Rover", "Spot"]
  • 16. Java  8  supports  Lambda  Expressions [Ginger, Spot, Fluffy, Rover] Predicate<Pet> carnivores = (pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat); List<Pet> carnivorousPets = pets.filter(carnivores).into(new ArrayList<Pet>()); ["Ginger", "Spot", "Rover"]
  • 17. Java  8  supports  Lambda  Expressions [Ginger, Spot, Fluffy, Rover] pets.filter((pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat))     .into(new ArrayList<Pet>()); ["Ginger", "Spot", "Rover"]
  • 18. Java  8  supports  Lambda  Expressions public class VetStay {     private Pet pet;     private Date startOfStay;     private String diagnosis;     public VetStay(Pet pet, Date startOfStay, String diagnosis) {         this.pet = pet;         this.startOfStay = startOfStay;         this.diagnosis = diagnosis;     } } List<VetStay> vetStays = pets.map(pet -> { return new VetStay(pet, new Date(), "sore paw");})                              .into(new ArrayList<VetStay>());
  • 19. Java  8  supports  Lambda  Expressions List<Pet> pets = Arrays.asList(Cat.called("Ginger"),         Dog.called("Spot"),         GuineaPig.called("Fluffy"),         Dog.called("Rover") ); assert pets.anyMatch(pet -> pet.getSpecies() == Dog)
  • 20. But  Func:onal  Programming  in  Java  today? Surely  this  is  madness!
  • 23. Immutable  Collec:ons Creating an immutable list List<String> colors = ImmutableList.of("red", "green", "blue"); Set<String> colors = ImmutableSet. of("red", "green", "blue"); Set<String> myColors = ImmutableSet.copyOf(colors); Creating an immutable copy
  • 24. No  more  returning  Null “Null sucks.” - Doug Lea “I call it my billion-dollar mistake.” - Sir Tony Hoare
  • 25. No  more  returning  Null What does a null return value mean? interface ClientService {     Client findByName(String name); } No matching client found (but we were expecting one)? No matching client found (but we’re cool with that)? Something went wrong?
  • 26. No  more  returning  Null Sometimes we might not return a client interface ClientService {     Optional<Client> findByName(String name); } This forces us to cater for this case in our code Optional<Client> clientOptional = clientService.findByName("Smith"); if (clientOptional.isPresent()) {     Client client = clientOptional.get(); } else {     // No client was found }
  • 27. No  more  returning  Null A person may not have a favorite color class Person {     Optional<Color> getFavoriteColor(); } Color colorToUse = person.getFavoriteColor().or(Blue) If not, use Blue
  • 28. And  lots  of  other  stuff...
  • 29. No  more  returning  Null What does a null return value mean? interface ClientService {     Client findByName(String name); } No matching client found (but we were expecting one)? No matching client found (but we’re cool with that)? Something went wrong?
  • 30. No  more  returning  Null Sometimes we might not return a client interface ClientService {     Optional<Client> findByName(String name); } This forces us to cater for this case in our code Optional<Client> clientOptional = clientService.findByName("Smith"); if (clientOptional.isPresent()) {     Client client = clientOptional.get(); } else {     // No client was found }
  • 31. No  more  returning  Null A person may not have a favorite color class Person {     Optional<Color> getFavoriteColor(); } Color colorToUse = person.getFavoriteColor().or(Blue) If not, use Blue
  • 32. lambdaj – DSL for manipulating collections in a functional style – Replace loops with more concise and readable code
  • 33. LambdaJ support many high level collection-related functions filter aggregate sort convert extract group
  • 34. Filtering  in  LambdaJ import static ch.lambdaj.Lambda.filter; import static org.hamcrest.Matchers.startsWith; . . . List<String> names = Arrays.asList("Aristotle", "Plato", "Socrates", "Pythagoras"); List<String> filteredNames = filter(startsWith("P"), names); assertThat(filteredNames, contains("Plato", "Pythagoras")); LambdaJ Hamcrest
  • 35. Filtering  in  LambdaJ ["Aristotle", "Plato", "Socrates", "Pythagoras"] filter(startsWith("P"), names) ["Plato", "Pythagoras"]
  • 36. Filtering  in  LambdaJ List<String> filteredNames = new ArrayList<>(); for(String name : names) {     if (name.startsWith("P")) {         filteredNames.add(name);     } } Old-style Java names.filter(name -> name.startsWith("P"))      .into(new ArrayList<String>()); Java 8 filter(startsWith("P"), names) Lambda J
  • 37. Filtering  in  LambdaJ List<Pet> pets = Arrays.asList(Cat.called("Ginger"),         Dog.called("Spot"),         GuineaPig.called("Fluffy"),          Dog.called("Rover")); List<Pet> sortedDogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); assertThat(sortedDogs, contains(Dog.called("Rover"), Dog.called("Spot")));
  • 38. Filtering  in  LambdaJ [Ginger, Spot, Fluffy, Rover] filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); [Rover, Spot]
  • 39. Sor:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover] sort(sortedDogs, on(Pet.class).getName()); [Fluffy, Ginger, Rover, Spot]
  • 40. Filtering  and  Sor:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover] List<Pet> filteredDogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); List<Pet> sortedDogs = sort(filteredDogs, on(Pet.class).getName()); [Rover, Spot]
  • 41. Extrac:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover] pets.filter(a -> a.getSpecies() == Dog) .map(e -> { return e.getName(); }) .sorted((a, b) -> a.compareTo(b))     .into(new ArrayList<Pet>()); Extracting with Java 8 ["Rover", "Spot"]
  • 42. Extrac:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover] List<Pet> dogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); List<String> dogNames = extract(dogs, on(Pet.class).getName()); List<String> sortedDogNames = sort(dogNames,on(String.class)); Extracting with LambdaJ ["Rover", "Spot"]
  • 43. Extrac:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover] List<Pet> filteredDogs = new ArrayList(); for(Pet pet : pets) {     if (pet.getSpecies() == Dog) {         filteredDogs.add(pet);     } } Collections.sort(filteredDogs, new Comparator<Pet>() {     @Override     public int compare(Pet pet, Pet pet1) {         return pet.getName().compareTo(pet1.getName());     } }); Extracting with old-style ["Rover", "Spot"] Java
  • 44. Extrac:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover] List<Pet> dogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); List<String> dogNames = extract(dogs, on(Pet.class).getName()); List<String> sortedDogNames = sort(dogNames,on(String.class)); Extracting with LambdaJ ["Rover", "Spot"]
  • 45. Conver:ng  in  LambdaJ List<VetStay> vetStays = pets.map(pet -> { return new VetStay(pet, new Date(), "sore paw");})                              .into(new ArrayList<VetStay>()); Converting with Java 8 convert(pets, toVetStay()); private Converter<Pet, VetStay> toVetStay() {     return new Converter<Pet, VetStay>() {         @Override         public VetStay convert(Pet pet) {             return new VetStay(pet, new Date(), "sore paw");         }     }; } Converting with LambdaJ
  • 46. Grouping  in  LambdaJ [Ginger, Spot, Fluffy, Rover] Group<Pet> petsBySpecies = group(pets, by(on(Pet.class).getSpecies())); List<Pet> dogs = petsBySpecies.find(Dog); [Spot,Rover]
  • 47. FlaOening  in  LambdaJ [[Spot, Rover], [Ginger], [Fluffy]] List<List<Pet>> petsBySpecies = ... List<Pet> allPets = flatten(petsBySpecies); [Spot, Rover, Ginger, Fluffy]
  • 48. Checking  existence  in  LambdaJ [Spot, Rover, Ginger, Fluffy] exists(pets, having(on(Pet.class).getSpecies(), is(Cat))) true
  • 49. Using  Predicates  in  LambdaJ Predicate<Pet> carnivores = (pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat); List<Pet> carnivorousPets = pets.filter(carnivores).into(new ArrayList<Pet>()); Java 8 Matcher<Pet> carnivore = new Predicate<Pet>() {     public boolean apply(Pet pet) {         return (pet.getSpecies() == Dog || pet.getSpecies() == Cat);     } }; List<Pet> carnivores = filter(carnivore, pets); LambdaJ
  • 50. Using  Aggregates  in  LambdaJ List<Pet> pets = Arrays.asList(Cat.called("Ginger"),         Dog.called("Spot"),         GuineaPig.called("Fluffy"),         Dog.called("Rover") ); int ageOfOldestPet = maxFrom(pets).getAge(); int ageOfYoungestPet = minFrom(pets).getAge(); int totalPetAges = sumFrom(pets).getAge();
  • 51. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS
  • 52. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING filter(having(on(TestOutcome.class).getResult(), is(SUCCESS)), outcomes); TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS
  • 53. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING filter(withResult(SUCCESS)), outcomes); private Matcher<?> withResult(TestResult expectedResult) {     return having(on(TestOutcome.class).getResult(), is(expectedResult)); } TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS
  • 54. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING filter(anyOf(withResult(SUCCESS), withResult(PENDING)), outcomes); TestOutcome  1 SUCCESSTestOutcome  2 SUCCESSTestOutcome  4 PENDING
  • 55. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING TestOutcome  2 Step  1 Step  2 Step  3 Step  4
  • 56. Some  real-­‐world  examples Tag Tag 1 TagProvider1 Tag TagProvider2 Tag Tag Tag Tag flatten(extract(TagProviders, on(TagProvider.class).getTags())); Tag Tag 1 Tag Tag Tag Tag Tag
  • 57. And  performance  in  all  that?
  • 58. Keeping  things  maintainable “Excessive use of Guava's functional programming idioms can lead to verbose, confusing, unreadable, and inefficient code.” - the Guava team Can also be true of LambdaJ
  • 59. Keeping  things  maintainable RULE 1 Use a functional style when it makes the intent more readable
  • 60. Keeping  things  maintainable sort(extract(filter(having(on(Pet.class).getSpecies(), is(Dog)), pets), on(Pet.class).getName()), on(String.class)); List<Pet> dogs = filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); List<String> dogNames = extract(dogs, on(Pet.class).getName()); List<String> sortedDogNames = sort(dogNames, on(String.class));
  • 61. Keeping  things  maintainable RULE 2 One-liners are not always better
  • 62. Keeping  things  maintainable convert(pets,         new Converter<Pet, VetStay>() {                     @Override                     public VetStay convert(Pet pet) {                         return new VetStay(pet, new Date(), "sore paw");                     }         } ); convert(pets, toVetStay()); private Converter<Pet, VetStay> toVetStay() {     return new Converter<Pet, VetStay>() {         @Override         public VetStay convert(Pet pet) {             return new VetStay(pet, new Date(), "sore paw");         }     }; }
  • 63. Keeping  things  maintainable RULE 3 Write your own domain-specific matchers
  • 64. Keeping  things  maintainable private Matcher<?> withResult(TestResult expectedResult) {     return having(on(TestOutcome.class).getResult(), is(expectedResult)); } filter(withResult(SUCCESS)), outcomes); select(not(withResult(SUCCESS))), outcomes); select(anyOf(withResult(SKIPPED), withResult(IGNORED)), outcomes);
  • 65. Thank You John  Ferguson  Smart john.smart@wakaleo.com  h2p://www.wakaleo.com Twi2er:  wakaleo