SlideShare a Scribd company logo
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 FP overview Sandwich algorithm FP main features Code samples Business Logic with FP FP libraries for Java
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 Take a bread Spread bread with butter Put cheese on the bread return result 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 Take a lower Spread lower with middle Put upper on the middle return result 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 Take a lower if  mode = ‘put’ put  middle on lower   else spread  middle on lower   end if Put upper on the middle return result 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 spread put … createSandwich  is a  higher-order  function which takes another function as a parameter
FP main features What is Functional Programming? Closures and higher order functions Lazy evaluation Recursion as a mechanism for control flow Enforcement of referential transparency No side-effects  FP Languages Lisp  (AutoCad) Haskell, Scheme, Logo XSLT 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 a dd   :: I n teger -> Integer -> Integer add  x y   =  x + y 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 ones   = 1 : ones  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()); Pros Cons
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 Pros  Cons ?
FP: Pros and Cons Pros Reliable code Readable Reusable … Non-natural for human Non-natural for computer Performance Cons Example: Quick Sort algorithm
Code sample: Quicksort Quicksort in Haskell  qsort  [] = [] qsort  (x:xs) =  qsort   elts_lt_x   ++ [x]  ++ qsort   elts_greq_x   where elts_lt_x  = [y | y <- xs, y < x] elts_greq_x  = [y | y <- xs, y >= x]
Code sample: Quicksort qsort( a, lo, hi ) int a[], hi, lo; { int h, l, p, t; if (lo < hi) { l = lo; h = hi; p = a[hi]; do { while ((l < h) && (a[l] <= p)) l = l+1; while ((h > l) && (a[h] >= p)) h = h-1; if (l < h) { t = a[l]; a[l] = a[h]; a[h] = t; } }   while (l < h); t = a[l]; a[l] = a[hi]; a[hi] = t; qsort( a, lo, l-1 ); qsort( a, l+1, hi ); } }   Quicksort in C
FP: Pros and Cons Pros Reliable code Readable Reusable … Non-natural for human Non-natural for computer Performance 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 I hope this article has provided you with a good foundation for incorporating closures and higher order functions into your Java code, as well as giving you a glimpse of the beauty and effectiveness of functional programming.
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 (20)

Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
Siddique Ibrahim
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
Darwin Durand
 
Function template
Function templateFunction template
Function template
Kousalya M
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++
Davinder Kaur
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
Thesis Scientist Private Limited
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
Mario Fusco
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
Dhruvin Nakrani
 
Branching statements
Branching statementsBranching statements
Branching statements
ArunMK17
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
Awais Alam
 
Java Queue.pptx
Java Queue.pptxJava Queue.pptx
Java Queue.pptx
vishal choudhary
 
C function
C functionC function
C function
thirumalaikumar3
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
Darwin Durand
 
Function template
Function templateFunction template
Function template
Kousalya M
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
Rai University
 
Structure & Union in C++
Structure & Union in C++Structure & Union in C++
Structure & Union in C++
Davinder Kaur
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
Dhruvin Nakrani
 
Branching statements
Branching statementsBranching statements
Branching statements
ArunMK17
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 

Viewers also liked (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Veerabadra Badra
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
John Ferguson Smart Limited
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithn
Kumar
 
Java seminar
Java seminarJava seminar
Java seminar
devendrakhairwa
 
Recursion
RecursionRecursion
Recursion
baabtra.com - No. 1 supplier of quality freshers
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
Raffi Khatchadourian
 
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
Ganesh Samarthyam
 
2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)
Esmeraldo Jr Guimbarda
 
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)
Esmeraldo Jr Guimbarda
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
brianjihoonlee
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
Vijay Kalyan
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
Narendran Solai Sridharan
 
2java Oop
2java Oop2java Oop
2java Oop
Adil Jafri
 
Java Script - Object-Oriented Programming
Java Script - Object-Oriented ProgrammingJava Script - Object-Oriented Programming
Java Script - Object-Oriented Programming
intive
 
02 java programming basic
02  java programming basic02  java programming basic
02 java programming basic
Zeeshan-Shaikh
 
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...
Philip Schwarz
 
Fp java8
Fp java8Fp java8
Fp java8
Yanai Franchi
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithn
Kumar
 
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
Ganesh Samarthyam
 
2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)
Esmeraldo Jr Guimbarda
 
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)
Esmeraldo Jr Guimbarda
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
brianjihoonlee
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
Vijay Kalyan
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
James Brown
 
Java Script - Object-Oriented Programming
Java Script - Object-Oriented ProgrammingJava Script - Object-Oriented Programming
Java Script - Object-Oriented Programming
intive
 
02 java programming basic
02  java programming basic02  java programming basic
02 java programming basic
Zeeshan-Shaikh
 
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...
Philip Schwarz
 
Ad

Similar to Functional Programming In Java (20)

Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programming
Steve Zhang
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
Fangda Wang
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Thang Mai
 
Why you should care about functional programming
Why you should care about functional programmingWhy you should care about functional programming
Why you should care about functional programming
Dhananjay Nene
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
Jayaram Sankaranarayanan
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prashant Kalkar
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prateek Jain
 
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
SQLI
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
Samir Chekkal
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Jordan Parmer
 
Functional Programming 之二三事
Functional Programming 之二三事Functional Programming 之二三事
Functional Programming 之二三事
Leeheng Ma
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
Functional programming
Functional programmingFunctional programming
Functional programming
Christian Hujer
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmer
Shawn Button
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
The joy of functional programming
The joy of functional programmingThe joy of functional programming
The joy of functional programming
Steve Zhang
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Gentle Introduction to Scala
Gentle Introduction to ScalaGentle Introduction to Scala
Gentle Introduction to Scala
Fangda Wang
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Thang Mai
 
Why you should care about functional programming
Why you should care about functional programmingWhy you should care about functional programming
Why you should care about functional programming
Dhananjay Nene
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
Jayaram Sankaranarayanan
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prateek Jain
 
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
SQLI
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
Samir Chekkal
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Jordan Parmer
 
Functional Programming 之二三事
Functional Programming 之二三事Functional Programming 之二三事
Functional Programming 之二三事
Leeheng Ma
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
Luis Atencio
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmer
Shawn Button
 
Ad

More from Andrei Solntsev (20)

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

Recently uploaded (20)

Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
Edge AI and Vision Alliance
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
Edge AI and Vision Alliance
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 

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. Agenda FP overview Sandwich algorithm FP main features Code samples Business Logic with FP FP libraries for Java
  • 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. Sandwich algorithm Function createSandwich Take a bread Spread bread with butter Put cheese on the bread return result Imperative return put ( cheese, spread(butter, bread) ) Functional
  • 6. Sandwich algorithm If we want to use sausage instead of cheese ? Let’s pass sausage/cheese as input parameter No problems!
  • 7. Sandwich algorithm Take a lower Spread lower with middle Put upper on the middle return result Function createSandwich (lower, middle, upper) return put ( upper, spread(middle, lower) ) Function createSandwich (lower, middle, upper) No problems! bread butter sausage
  • 8. Sandwich algorithm If we want to put butter instead of spreading ? Imperative programming: Problem! Functional programming: not a problem
  • 9. Sandwich algorithm Take a lower if mode = ‘put’ put middle on lower else spread middle on lower end if Put upper on the middle return result Procedure createSandwich (lower, middle, upper, mode) Imperative programming: Problem! bread butter sausage put Alternative: create 2 different functions  Code duplication
  • 10. 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 spread put … createSandwich is a higher-order function which takes another function as a parameter
  • 11. FP main features What is Functional Programming? Closures and higher order functions Lazy evaluation Recursion as a mechanism for control flow Enforcement of referential transparency No side-effects FP Languages Lisp (AutoCad) Haskell, Scheme, Logo XSLT 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.
  • 12. Code Samples in Haskell a dd :: I n teger -> Integer -> Integer add  x y =  x + y 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
  • 13. Code Samples in Haskell ones = 1 : ones Infinite data structures numsFrom n = n : numsFrom (n+1) squares = map (^2) (numsfrom 0) take 5 squares => [0,1,4,9,16]
  • 14. Code Samples in Haskell Fibonacci sequence fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
  • 15. 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()); Pros Cons
  • 16. 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 Pros Cons ?
  • 17. FP: Pros and Cons Pros Reliable code Readable Reusable … Non-natural for human Non-natural for computer Performance Cons Example: Quick Sort algorithm
  • 18. Code sample: Quicksort Quicksort in Haskell qsort [] = [] qsort (x:xs) = qsort elts_lt_x ++ [x] ++ qsort elts_greq_x where elts_lt_x = [y | y <- xs, y < x] elts_greq_x = [y | y <- xs, y >= x]
  • 19. Code sample: Quicksort qsort( a, lo, hi ) int a[], hi, lo; { int h, l, p, t; if (lo < hi) { l = lo; h = hi; p = a[hi]; do { while ((l < h) && (a[l] <= p)) l = l+1; while ((h > l) && (a[h] >= p)) h = h-1; if (l < h) { t = a[l]; a[l] = a[h]; a[h] = t; } } while (l < h); t = a[l]; a[l] = a[hi]; a[hi] = t; qsort( a, lo, l-1 ); qsort( a, l+1, hi ); } } Quicksort in C
  • 20. FP: Pros and Cons Pros Reliable code Readable Reusable … Non-natural for human Non-natural for computer Performance 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.
  • 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. Conclusion I hope this article has provided you with a good foundation for incorporating closures and higher order functions into your Java code, as well as giving you a glimpse of the beauty and effectiveness of functional programming.
  • 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/