SlideShare a Scribd company logo
1 of 39
Functional Programming in Java Java technology seminar SECR, 2007 Andrei Solntsev
Purpose S eminar   gives an  overview of   Functional Programming methods and  its applications in Java  for coding Business Logic and  its customization
Agenda ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
FP Overview Computation is executing statements to change the program state. Imperative programming Functional programming Computation is evaluation of expressions The focus is on  what , not  how Expressions  are formed by using functions to combine basic values Program  consists of a sequence of commands.
Sandwich algorithm Function  createSandwich ,[object Object],[object Object],[object Object],[object Object],Imperative return put ( cheese, spread(butter, bread) ) Functional
Sandwich algorithm If we want to use  sausage  instead of  cheese  ? Let’s pass sausage/cheese as input parameter No problems!
Sandwich algorithm ,[object Object],[object Object],[object Object],[object Object],Function  createSandwich (lower, middle, upper) return put ( upper, spread(middle, lower) ) Function  createSandwich (lower, middle, upper) No problems! bread butter sausage
Sandwich algorithm If we want to  put  butter instead of  spreading  ? Imperative  programming: Problem! Functional  programming: not a problem
Sandwich algorithm ,[object Object],[object Object],[object Object],[object Object],Procedure  createSandwich (lower, middle, upper, mode) Imperative  programming: Problem! bread butter sausage put Alternative: create 2 different functions   Code duplication
Sandwich algorithm return put ( upper, action (middle, lower) ) Function  createSandwich (lower, middle, upper,  action ) Functional  programming: not a problem bread butter sausage put Action  is a function with 2 parameters ,[object Object],[object Object],[object Object],createSandwich  is a  higher-order  function which takes another function as a parameter
FP main features What is Functional Programming? ,[object Object],[object Object],[object Object],[object Object],[object Object],FP Languages ,[object Object],[object Object],[object Object],Where a traditional imperative program might  use a loop to traverse a list, a functional style would often use a  higher-order function, map, that takes as arguments a function and  a list, applies the function to each element of the list,  and returns a list of the results.
Code Samples in Haskell ,[object Object],[object Object],functions inc  :: Integer -> Integer inc   = add 1  map   :: (a->b) -> [a] -> [b] map  f  []       =  [] map  f (x:xs)    =  f x : map f xs zip  (x:xs) (y:ys)  = (x,y) : zip xs ys zip   xs     ys     = []  Uncurried function F unction can be returned as a value  ! Higher-order function curried function
Code Samples in Haskell ,[object Object],Infinite   data structures numsFrom n   =   n   :   numsFrom (n+1)  squares   = map (^2) (numsfrom 0)  take 5 squares => [0,1,4,9,16]
Code Samples in Haskell Fibonacci sequence  fib   = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
FP-Style code example in Java java.util.Properties Properties properties = new Properties(); properties.setProperty(“firstName&quot;, groom.getFirstName()); properties.setProperty(“lastName&quot;, groom.getLastName()); properties.setProperty(“salary&quot;, groom.getSalary()); return  parameters; return Imperative Functional return  new Properties() .setProperty(“firstName&quot;, groom.getFirstName()) .setProperty(“lastName&quot;, groom.getLastName()) .setProperty(“salary&quot;, groom.getSalary()); ,[object Object],[object Object]
FP-Style code example In Java StringBuffer StringBuffer sb = new StringBuffer(); sb.append(“a”); sb.append(“b”); sb.append(“c”); return sb.toString(); return new StringBuffer() .append(“a”); .append(“b”); .append(“c”) .toString(); Imperative Functional ,[object Object],[object Object]
FP: Pros and Cons Pros ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Cons Example: Quick Sort algorithm
Code sample: Quicksort ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Code sample: Quicksort ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Quicksort in C
FP: Pros and Cons Pros ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Cons Example: Quick Sort algorithm In Java, FP suits for implementing Business Logic Programs are easier to design, write and maintain, but programmer  has  less control over the machine.
Business logic with FP GroomFilter List  suitableGrooms  = new ArrayList(); for (groom in allGrooms) { if ( minAge > -1 && groom.getAge() < minAge ) continue; if (maxAge > -1 && groom.getAge() > maxAge) continue; suitableGrooms .add(groom); } return  suitableGrooms ; List filterGrooms(List allGrooms ,  int minAge, int maxAge) If age is -1 then Don’t check age
Business logic with FP GroomFilter List suitableGrooms = new ArrayList(); for (groom in allGrooms) { if ( groomChecker .accept(groom)) suitableGrooms.add(groom); } return suitableGrooms; List filterGrooms(List allGrooms,  Filter groomChecker ) Pass function as parameter
Business logic with FP public interface  Filter   { /** * Method defines whether given object is accepted. * @param obj any Object * @return true iff object is accepted */ boolean  accept (Object obj); }
Business logic with FP public interface  Filter   { boolean  accept (Object obj); public static final Filter  ACCEPT  = new Filter() { public boolean accept(Object obj){ return true; } }; public static final Filter  NOT_NULL  = new Filter() { public boolean accept(Object obj){ return obj!=null; } }; public static final Filter  NEGATE ..; public static final Filter  IS_NULL  = …; } Predefined values
Business logic with FP Client 1 List suitableGrooms grooms = GroomFilter.filterGrooms(…, new Filter() { public boolean accept(Object obj) {   return ((Groom) obj).getAge() > 23; } } ); Client 2 List suitableGrooms = GroomFilter.filterGrooms(…, Filter.ACCEPT ); Closure  –  object representing a function Anonymous classes are often used as closures
25 th  frame 25 th  frame
Parameterized Closures StringFilter public class  StringFilter  implements  Filter { public static  startsWith (final String  prefix ) { return  new Filter {   public boolean  accept (Object o){ return ((String) o). startsWith (prefix);   } }; } public static  endsWith  (final String  postfix ) {…} public static  contains  (final String  substring ) {…} public static  matches  (final String  regexp ) {…} };
Composition of functions Composition of functions: AND public class  AND  implements  Filter { public AND (Filter filter1, Filter filter2) { this.filter1 = filter1; this.filter2 = filter2; } public boolean  accept (Object obj) { return  filter1.accept (obj)  &&   filter2.accept (obj); } };
FP Applications: Filters FilteredIterator public class FilteredIterator implements Iterator { public  FilteredIterator ( Iterator iterator ,  Filter filter ); } CollectionsUtils static List  collectList ( Iterator it ); static Set  collectSet ( Iterator it ); static List  filterList  ( List original ,  Filter filter ); static Set  filterSet  ( Set originalSet ,  Filter filter );
FP Applications: Filters Given: a list of all grooms’ names. Goal: find all names with prefix “Mr.” List  gentlemen  = new LinkedList(); for (Iterator it =  groomsNames .iterator(); it.hasNext(); ) { String name = (String) it.next(); if (name != null &&  name.startsWith(“Mr.”)) {   gentlemen .add(name); } } return  gentlemen ; Imperative
FP Applications: Filters Functional return  CollectionsUtils . filterList( allGrooms, StringFilter.startsWith( “Mr.” ) ) ; Given: a list of all grooms’ names. Goal: find all names with prefix “Mr.”
FP Applications: Transformers Transformer public interface Transformer { Object  transform ( Object sourceObject ); } ListTransformer public class ListTransformer { public List  transform ( List sourceList ,  Transformer transformer ); }
FP Applications: Transformers Given: list of Grooms Goal: create list grooms’ names List  groomsNames  = new ArrayList(); for (Iterator it =  allGrooms .iterator(); it.hasNext(); ) { Groom groom = (Groom) it.next(); groomsNames .add(groom.getName()); } return  groomsNames ; Imperative
FP Applications: Transformers return  ListTransformer. transform(  allGrooms , new Transformer () {   public Object transform(Object obj)   { return ((Groom) obj).getName();   } } ) ; Functional Given: list of Grooms Goal: create list grooms’ names
Business Logic customization Example using Plexus container import org.codehaus.plexus.embed.Embedder;  public List findSuitableGrooms(Client woman) { Filter   clientGroomFilter   = ( Filter )  embedder.lookup (  “ groomFilter” ,  woman.getName() );  return GroomFilter.filterGrooms( allGrooms,  clientGroomFilter ); }
Business Logic customization META-INF/plexus/components.xml  <component-set> <components> <component> <role> groomFilter </role> <role-hint> default </role-hint> <implementation> examples. Filter.ACCEPT </implementation> </component> <component> <role> groomFilter </role> <role-hint> Maril Strip </role-hint> <implementation> examples. filters.OlderThan25 </implementation> </component> <component> <role> groomFilter </role> <role-hint> Jenifer Lopez </role-hint> <implementation> examples. filters.SalaryBiggerThan10000 </implementation> </component> </components> </component-set>
Conclusion ,[object Object]
FP Libraries for Java Commons   Functors : Function Objects for Java http://jakarta.apache.org/commons/sandbox/functor JGA: Generic Algorithms for Java   http:// jga.sourceforge.net http://plexus.codehaus.org
Articles Functional programming in the Java language http ://www-128.ibm.com/developerworks/library-combined/j-fp.html Use recursion effectively in XSL http://www-128.ibm.com/developerworks/xml/library/x-xslrecur Why Functional Programming Matters http:// www.math.chalmers.se/~rjmh/Papers/whyfp.html Introduction to Haskell http:// www.haskell.org/tutorial/

More Related Content

What's hot

Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
Ankur Gupta
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
g3_nittala
 
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
Mite Mitreski
 

What's hot (20)

Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
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
 
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
 
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
 
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
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
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
 
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 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
 
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
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
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
 
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
 
Java Generics
Java GenericsJava Generics
Java Generics
 
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
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Kpi driven-java-development-fn conf
Kpi driven-java-development-fn confKpi driven-java-development-fn conf
Kpi driven-java-development-fn conf
 

Viewers also liked

Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithn
Kumar
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
brianjihoonlee
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 

Viewers also liked (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithn
 
Java seminar
Java seminarJava seminar
Java seminar
 
Recursion
RecursionRecursion
Recursion
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)
 
TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
2java Oop
2java Oop2java Oop
2java Oop
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Java Script - Object-Oriented Programming
Java Script - Object-Oriented ProgrammingJava Script - Object-Oriented Programming
Java Script - Object-Oriented Programming
 
02 java programming basic
02  java programming basic02  java programming basic
02 java programming basic
 
Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...
Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...
Understanding Java 8 Lambdas and Streams - Part 1 - Lambda Calculus, Lambda...
 
Fp java8
Fp java8Fp java8
Fp java8
 

Similar to Functional Programming In Java

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 

Similar to Functional Programming In Java (20)

Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 

More from Andrei Solntsev

More from Andrei Solntsev (20)

Тройничок: Selenide для Web, Android и iOS
Тройничок: Selenide для Web, Android и iOSТройничок: Selenide для Web, Android и iOS
Тройничок: Selenide для Web, Android и iOS
 
Flaky tests. Метод.
Flaky tests. Метод. Flaky tests. Метод.
Flaky tests. Метод.
 
Батл: Тесты или не тесты?
Батл: Тесты или не тесты?Батл: Тесты или не тесты?
Батл: Тесты или не тесты?
 
Как получить чёрный пояс по программированию
Как получить чёрный пояс по программированиюКак получить чёрный пояс по программированию
Как получить чёрный пояс по программированию
 
Selenide puzzlers @ devclub.eu
Selenide puzzlers @ devclub.euSelenide puzzlers @ devclub.eu
Selenide puzzlers @ devclub.eu
 
What is master @ SeleniumConf 2015
What is master @ SeleniumConf 2015What is master @ SeleniumConf 2015
What is master @ SeleniumConf 2015
 
50 оттенков play!
50 оттенков play!50 оттенков play!
50 оттенков play!
 
Liquibase & Flyway @ Baltic DevOps
Liquibase & Flyway @ Baltic DevOpsLiquibase & Flyway @ Baltic DevOps
Liquibase & Flyway @ Baltic DevOps
 
Экономически эффективный процесс тестирования (Codefest 2015)
Экономически эффективный процесс тестирования (Codefest 2015)Экономически эффективный процесс тестирования (Codefest 2015)
Экономически эффективный процесс тестирования (Codefest 2015)
 
Bullshit driven development
Bullshit driven developmentBullshit driven development
Bullshit driven development
 
Good test = simple test (with selenide)
Good test = simple test (with selenide)Good test = simple test (with selenide)
Good test = simple test (with selenide)
 
The fast and the continuous - SQA Days 16
The fast and the continuous - SQA Days 16The fast and the continuous - SQA Days 16
The fast and the continuous - SQA Days 16
 
The fast and the continuous (SeleniumCamp 2014)
The fast and the continuous (SeleniumCamp 2014)The fast and the continuous (SeleniumCamp 2014)
The fast and the continuous (SeleniumCamp 2014)
 
Liquibase: Enterprise Edition
Liquibase: Enterprise EditionLiquibase: Enterprise Edition
Liquibase: Enterprise Edition
 
Static website-generators
Static website-generatorsStatic website-generators
Static website-generators
 
Extreme banking
Extreme bankingExtreme banking
Extreme banking
 
Kiss.devclub ee.est
Kiss.devclub ee.estKiss.devclub ee.est
Kiss.devclub ee.est
 
Real-life unit tests
Real-life unit testsReal-life unit tests
Real-life unit tests
 
WTF Code @ jug.lv
WTF Code @ jug.lvWTF Code @ jug.lv
WTF Code @ jug.lv
 
Android (Devclub.eu, 30.03.2010)
Android (Devclub.eu, 30.03.2010)Android (Devclub.eu, 30.03.2010)
Android (Devclub.eu, 30.03.2010)
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Functional Programming In Java

  • 1. Functional Programming in Java Java technology seminar SECR, 2007 Andrei Solntsev
  • 2. Purpose S eminar gives an overview of Functional Programming methods and its applications in Java for coding Business Logic and its customization
  • 3.
  • 4. FP Overview Computation is executing statements to change the program state. Imperative programming Functional programming Computation is evaluation of expressions The focus is on what , not how Expressions are formed by using functions to combine basic values Program consists of a sequence of commands.
  • 5.
  • 6. Sandwich algorithm If we want to use sausage instead of cheese ? Let’s pass sausage/cheese as input parameter No problems!
  • 7.
  • 8. Sandwich algorithm If we want to put butter instead of spreading ? Imperative programming: Problem! Functional programming: not a problem
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. Code Samples in Haskell Fibonacci sequence fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21. Business logic with FP GroomFilter List suitableGrooms = new ArrayList(); for (groom in allGrooms) { if ( minAge > -1 && groom.getAge() < minAge ) continue; if (maxAge > -1 && groom.getAge() > maxAge) continue; suitableGrooms .add(groom); } return suitableGrooms ; List filterGrooms(List allGrooms , int minAge, int maxAge) If age is -1 then Don’t check age
  • 22. Business logic with FP GroomFilter List suitableGrooms = new ArrayList(); for (groom in allGrooms) { if ( groomChecker .accept(groom)) suitableGrooms.add(groom); } return suitableGrooms; List filterGrooms(List allGrooms, Filter groomChecker ) Pass function as parameter
  • 23. Business logic with FP public interface Filter { /** * Method defines whether given object is accepted. * @param obj any Object * @return true iff object is accepted */ boolean accept (Object obj); }
  • 24. Business logic with FP public interface Filter { boolean accept (Object obj); public static final Filter ACCEPT = new Filter() { public boolean accept(Object obj){ return true; } }; public static final Filter NOT_NULL = new Filter() { public boolean accept(Object obj){ return obj!=null; } }; public static final Filter NEGATE ..; public static final Filter IS_NULL = …; } Predefined values
  • 25. Business logic with FP Client 1 List suitableGrooms grooms = GroomFilter.filterGrooms(…, new Filter() { public boolean accept(Object obj) { return ((Groom) obj).getAge() > 23; } } ); Client 2 List suitableGrooms = GroomFilter.filterGrooms(…, Filter.ACCEPT ); Closure – object representing a function Anonymous classes are often used as closures
  • 26. 25 th frame 25 th frame
  • 27. Parameterized Closures StringFilter public class StringFilter implements Filter { public static startsWith (final String prefix ) { return new Filter { public boolean accept (Object o){ return ((String) o). startsWith (prefix); } }; } public static endsWith (final String postfix ) {…} public static contains (final String substring ) {…} public static matches (final String regexp ) {…} };
  • 28. Composition of functions Composition of functions: AND public class AND implements Filter { public AND (Filter filter1, Filter filter2) { this.filter1 = filter1; this.filter2 = filter2; } public boolean accept (Object obj) { return filter1.accept (obj) && filter2.accept (obj); } };
  • 29. FP Applications: Filters FilteredIterator public class FilteredIterator implements Iterator { public FilteredIterator ( Iterator iterator , Filter filter ); } CollectionsUtils static List collectList ( Iterator it ); static Set collectSet ( Iterator it ); static List filterList ( List original , Filter filter ); static Set filterSet ( Set originalSet , Filter filter );
  • 30. FP Applications: Filters Given: a list of all grooms’ names. Goal: find all names with prefix “Mr.” List gentlemen = new LinkedList(); for (Iterator it = groomsNames .iterator(); it.hasNext(); ) { String name = (String) it.next(); if (name != null && name.startsWith(“Mr.”)) { gentlemen .add(name); } } return gentlemen ; Imperative
  • 31. FP Applications: Filters Functional return CollectionsUtils . filterList( allGrooms, StringFilter.startsWith( “Mr.” ) ) ; Given: a list of all grooms’ names. Goal: find all names with prefix “Mr.”
  • 32. FP Applications: Transformers Transformer public interface Transformer { Object transform ( Object sourceObject ); } ListTransformer public class ListTransformer { public List transform ( List sourceList , Transformer transformer ); }
  • 33. FP Applications: Transformers Given: list of Grooms Goal: create list grooms’ names List groomsNames = new ArrayList(); for (Iterator it = allGrooms .iterator(); it.hasNext(); ) { Groom groom = (Groom) it.next(); groomsNames .add(groom.getName()); } return groomsNames ; Imperative
  • 34. FP Applications: Transformers return ListTransformer. transform( allGrooms , new Transformer () { public Object transform(Object obj) { return ((Groom) obj).getName(); } } ) ; Functional Given: list of Grooms Goal: create list grooms’ names
  • 35. Business Logic customization Example using Plexus container import org.codehaus.plexus.embed.Embedder; public List findSuitableGrooms(Client woman) { Filter clientGroomFilter = ( Filter ) embedder.lookup ( “ groomFilter” , woman.getName() ); return GroomFilter.filterGrooms( allGrooms, clientGroomFilter ); }
  • 36. Business Logic customization META-INF/plexus/components.xml <component-set> <components> <component> <role> groomFilter </role> <role-hint> default </role-hint> <implementation> examples. Filter.ACCEPT </implementation> </component> <component> <role> groomFilter </role> <role-hint> Maril Strip </role-hint> <implementation> examples. filters.OlderThan25 </implementation> </component> <component> <role> groomFilter </role> <role-hint> Jenifer Lopez </role-hint> <implementation> examples. filters.SalaryBiggerThan10000 </implementation> </component> </components> </component-set>
  • 37.
  • 38. FP Libraries for Java Commons Functors : Function Objects for Java http://jakarta.apache.org/commons/sandbox/functor JGA: Generic Algorithms for Java http:// jga.sourceforge.net http://plexus.codehaus.org
  • 39. Articles Functional programming in the Java language http ://www-128.ibm.com/developerworks/library-combined/j-fp.html Use recursion effectively in XSL http://www-128.ibm.com/developerworks/xml/library/x-xslrecur Why Functional Programming Matters http:// www.math.chalmers.se/~rjmh/Papers/whyfp.html Introduction to Haskell http:// www.haskell.org/tutorial/