Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

Functional programming in java

9.077 Aufrufe

Veröffentlicht am

Functional programming is all the rage. It can undoubtedly produce cleaner and more expressive code, but why switch to Scala or wait for Java 8? In fact, there are many ways to dramatically improve your Java code quality by using a more functional style today. This presentation discusses how techniques such as functional programming, using fluent APIs, and other clean coding practices can make your code more concise, more readable, and much easier to maintain. But more importantly, you will learn about libraries such as LambdaJ and Google Guava that make this possible today with your existing Java code base.

  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD THAT BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download Full doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download PDF EBOOK here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download EPUB Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... Download doc Ebook here { http://bit.ly/2m6jJ5M } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book that can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer that is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story That Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths that Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • DOWNLOAD FULL BOOKS, INTO AVAILABLE FORMAT ......................................................................................................................... ......................................................................................................................... ,DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ,DOWNLOAD FULL. doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier

Functional programming in java

  1. 1. Improve Your Java Code, Functional-Style - Now! John  Ferguson  Smart john.smart@wakaleo.com  h2p://www.wakaleo.com Twi2er:  wakaleo
  2. 2. So who is this guy, anyway? Consulta nt Trainer Mentor Author Speaker Coder John Fer guson S mar t
  3. 3. f(x,y) = x + yFunc:onal  Programming  is  the  new  black
  4. 4. Immutability  is  your  friend
  5. 5. Avoid  nasty  side-­‐effects
  6. 6. Benefit  from  concurrency
  7. 7. No  more  messy  loops
  8. 8. HowWhat
  9. 9. Func:onal  Programming  in  Java Coming  to  a  JVM  near  you  the  summer  of  2013
  10. 10. Java  8  supports  Lambda  ExpressionsList<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. 11. Java  8  supports  Lambda  Expressions["Aristotle", "Plato", "Socrates", "Pythagoras"] names.filter(name -> name.startsWith("P"))      .into(new ArrayList<String>()); ["Plato", "Pythagoras"]
  12. 12. Java  8  supports  Lambda  Expressionspublic 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. 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. 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. 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. 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. 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. 18. Java  8  supports  Lambda  Expressionspublic 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. 19. Java  8  supports  Lambda  ExpressionsList<Pet> pets = Arrays.asList(Cat.called("Ginger"),        Dog.called("Spot"),        GuineaPig.called("Fluffy"),        Dog.called("Rover"));assert pets.anyMatch(pet -> pet.getSpecies() == Dog)
  20. 20. But  Func:onal  Programming  in  Java  today?Surely  this  is  madness!
  21. 21. Google Guava
  22. 22. Immutable  Collec:onsDefensiveThread-safeEfficient
  23. 23. Immutable  Collec:ons Creating an immutable listList<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. 24. No  more  returning  Null“Null sucks.” - Doug Lea“I call it my billion-dollar mistake.” - Sir Tony Hoare
  25. 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. 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 codeOptional<Client> clientOptional = clientService.findByName("Smith");if (clientOptional.isPresent()) {    Client client = clientOptional.get();} else {    // No client was found}
  27. 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. 28. And  lots  of  other  stuff...
  29. 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. 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 codeOptional<Client> clientOptional = clientService.findByName("Smith");if (clientOptional.isPresent()) {    Client client = clientOptional.get();} else {    // No client was found}
  31. 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. 32. lambdaj– DSL for manipulating collections in a functional style– Replace loops with more concise and readable code
  33. 33. LambdaJ support many high levelcollection-related functions filter aggregate sort convertextract group
  34. 34. Filtering  in  LambdaJimport 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. 35. Filtering  in  LambdaJ["Aristotle", "Plato", "Socrates", "Pythagoras"] filter(startsWith("P"), names) ["Plato", "Pythagoras"]
  36. 36. Filtering  in  LambdaJList<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. 37. Filtering  in  LambdaJList<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. 38. Filtering  in  LambdaJ [Ginger, Spot, Fluffy, Rover]filter(having(on(Pet.class).getSpecies(), is(Dog)), pets); [Rover, Spot]
  39. 39. Sor:ng  in  LambdaJ [Ginger, Spot, Fluffy, Rover]sort(sortedDogs, on(Pet.class).getName()); [Fluffy, Ginger, Rover, Spot]
  40. 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. 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. 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. 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. 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. 45. Conver:ng  in  LambdaJList<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. 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. 47. FlaOening  in  LambdaJ [[Spot, Rover], [Ginger], [Fluffy]]List<List<Pet>> petsBySpecies = ...List<Pet> allPets = flatten(petsBySpecies); [Spot, Rover, Ginger, Fluffy]
  48. 48. Checking  existence  in  LambdaJ [Spot, Rover, Ginger, Fluffy]exists(pets, having(on(Pet.class).getSpecies(), is(Cat))) true
  49. 49. Using  Predicates  in  LambdaJPredicate<Pet> carnivores = (pet) -> (pet.getSpecies() == Dog || pet.getSpecies() == Cat);List<Pet> carnivorousPets = pets.filter(carnivores).into(new ArrayList<Pet>()); Java 8Matcher<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. 50. Using  Aggregates  in  LambdaJList<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. 51. Some  real-­‐world  examplesTestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS
  52. 52. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDINGfilter(having(on(TestOutcome.class).getResult(), is(SUCCESS)), outcomes); TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS
  53. 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. 54. Some  real-­‐world  examples TestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDINGfilter(anyOf(withResult(SUCCESS), withResult(PENDING)), outcomes); TestOutcome  1 SUCCESSTestOutcome  2 SUCCESSTestOutcome  4 PENDING
  55. 55. Some  real-­‐world  examplesTestOutcome  1 SUCCESS TestOutcome  2 SUCCESS TestOutcome  3 TestOutcome  4 FAILURE PENDING TestOutcome  2 Step  1 Step  2 Step  3 Step  4
  56. 56. Some  real-­‐world  examples Tag Tag 1 TagProvider1 Tag TagProvider2 Tag Tag Tag Tagflatten(extract(TagProviders, on(TagProvider.class).getTags())); Tag Tag 1 Tag Tag Tag Tag Tag
  57. 57. And  performance  in  all  that?
  58. 58. Keeping  things  maintainable“Excessive use of Guavas functional programming idioms canlead to verbose, confusing, unreadable, and inefficient code.” - the Guava team Can also be true of LambdaJ
  59. 59. Keeping  things  maintainable RULE 1Use a functional style when it makes the intent more readable
  60. 60. Keeping  things  maintainablesort(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. 61. Keeping  things  maintainable RULE 2 One-liners are not always better
  62. 62. Keeping  things  maintainableconvert(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. 63. Keeping  things  maintainable RULE 3Write your own domain-specific matchers
  64. 64. Keeping  things  maintainableprivate 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. 65. Thank You John  Ferguson  Smartjohn.smart@wakaleo.com  h2p://www.wakaleo.com Twi2er:  wakaleo

×