0% found this document useful (0 votes)
3 views

24 1228 - Functional Programming Pre-reading

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

24 1228 - Functional Programming Pre-reading

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Pre-Reading: Functional Programming in Java

Overview
Functional programming is a paradigm that treats computation as the eval-
uation of mathematical functions and avoids changing-state and mutable
data. In Java, functional programming capabilities have been enhanced sig-
nificantly since the release of Java 8. This pre-reading document covers key
concepts, syntax, and examples to prepare you for Java functional program-
ming.

Core Concepts
1. Functional Interfaces
A functional interface is an interface with exactly one abstract method. Com-
mon examples in Java include:

• java.util.function.Predicate<T> - Takes one argument and re-


turns a boolean.

• java.util.function.Function<T,R> - Takes one argument and re-


turns a result.

• java.util.function.Consumer<T> - Takes one argument and returns


no result.

• java.util.function.Supplier<T> - Takes no arguments and returns


a result.

1
1 import java . util . function . Predicate ;
2

3 public class PredicateExample {


4 public static void main ( String [] args ) {
5 Predicate < String > isLongerThan5 = s ->
s . length () > 5;
6

7 System . out . println ( isLongerThan5 . test ( " Hello " ) ) ;


// Output : false
8 System . out . println ( isLongerThan5 . test ( " Functional
Programming " ) ) ; // Output : true
9 }
10 }
Listing 1: Example: Predicate Functional Interface

2. Lambda Expressions
Lambda expressions provide a clear and concise way to represent a functional
interface instance. Syntax:

• (parameters) -> expression

• (parameters) -> {statements}

1 import java . util . function . Function ;


2

3 public class LambdaExample {


4 public static void main ( String [] args ) {
5 Function < Integer , Integer > square = x -> x * x ;
6

7 System . out . println ( square . apply (5) ) ; //


Output : 25
8 }
9 }
Listing 2: Example: Using Lambda with a Function

2
3. Streams API
Streams are a powerful abstraction for working with sequences of data. They
support operations such as filtering, mapping, and reducing.
1 import java . util . Arrays ;
2 import java . util . List ;
3

4 public class StreamsExample {


5 public static void main ( String [] args ) {
6 List < String > names = Arrays . asList ( " Alice " ,
" Bob " , " Charlie " , " David " ) ;
7

8 names . stream ()
9 . filter ( name -> name . startsWith ( " A " ) )
10 . map ( String :: toUpperCase )
11 . forEach ( System . out :: println ) ; // Output :
ALICE
12 }
13 }
Listing 3: Example: Streams for Filtering and Mapping

Additional Examples
Example: Filtering a List with Streams
1 import java . util . Arrays ;
2 import java . util . List ;
3 import java . util . stream . Collectors ;
4

5 public class S tr e a mF i l te r E xa m p le {
6 public static void main ( String [] args ) {
7 List < Integer > numbers = Arrays . asList (10 , 15 ,
20 , 25 , 30) ;
8

9 // Filter numbers greater than 20


10 List < Integer > filteredNumbers = numbers . stream ()
11 . filter ( num
->

3
num >
20)
12 . collect ( Collectors . toList
13

14 System . out . println ( filteredNumbers ) ; // Output :


[25 , 30]
15 }
16 }
Listing 4: Filtering a List with Streams

Example: Combining Predicates


1 import java . util . function . Predicate ;
2

3 public class P r e d i c a t e C o m b i n a t i o n {
4 public static void main ( String [] args ) {
5 Predicate < Integer > isEven = n -> n % 2 == 0;
6 Predicate < Integer > isGreaterThan10 = n -> n >
10;
7

8 // Combine predicates : numbers that are even


and greater than 10
9 Predicate < Integer > co mbined Predic ate =
isEven . and ( isGreaterThan10 ) ;
10

11 System . out . println ( co mbined Predic ate . test (12) ) ;


// Output : true
12 System . out . println ( co mbined Predic ate . test (9) ) ;
// Output : false
13 }
14 }
Listing 5: Combining Predicates

Example: Mapping and Reducing with Streams


1 import java . util . Arrays ;
2 import java . util . List ;

4
3

4 public class MapReduceExample {


5 public static void main ( String [] args ) {
6 List < Integer > numbers = Arrays . asList (1 , 2 , 3 ,
4 , 5) ;
7

8 // Find the sum of squares


9 int sumOfSquares = numbers . stream ()
10 . map ( num -> num * num )
11 . reduce (0 ,
Integer :: sum ) ;
12

13 System . out . println ( sumOfSquares ) ; // Output : 55


14 }
15 }
Listing 6: Mapping and Reducing with Streams

Example: Custom Functional Interface


1 @Fu n c t i o n a l I n t e r f a c e
2 interface Calculator {
3 int calculate ( int a , int b ) ;
4 }
5

6 public class C u s t o m F u n c t i o n a l I n t e r f a c e {
7 public static void main ( String [] args ) {
8 Calculator add = (a , b ) -> a + b ;
9 Calculator multiply = (a , b ) -> a * b ;
10

11 System . out . println ( add . calculate (5 , 3) ) ;


// Output : 8
12 System . out . println ( multiply . calculate (5 , 3) ) ;
// Output : 15
13 }
14 }
Listing 7: Custom Functional Interface

5
Example: Using Method References
1 import java . util . Arrays ;
2 import java . util . List ;
3

4 public class M e t h o d R e f e r e n c e E x a m p l e {
5 public static void main ( String [] args ) {
6 List < String > names = Arrays . asList ( " Alice " ,
" Bob " , " Charlie " ) ;
7

8 // Print each name using method reference


9 names . forEach ( System . out :: println ) ;
10 // Output :
11 // Alice
12 // Bob
13 // Charlie
14 }
15 }
Listing 8: Using Method References

Key Advantages
• Improves readability and maintainability.

• Simplifies parallel programming.

• Reduces boilerplate code.

Best Practices
• Use lambda expressions and streams judiciously to maintain readabil-
ity.

• Avoid side effects in lambda expressions to ensure functional purity.

• Leverage method references where possible (e.g., ClassName::methodName).

6
Further Reading
• Official Java Documentation: https://docs.oracle.com/javase/8/docs/api/

• ”Java 8 in Action” by Raoul-Gabriel Urma, Mario Fusco, and Alan


Mycroft

• Online tutorials and practice exercises on https://www.baeldung.com/

You might also like