24 1228 - Functional Programming Pre-reading
24 1228 - Functional Programming Pre-reading
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:
1
1 import java . util . function . Predicate ;
2
2. Lambda Expressions
Lambda expressions provide a clear and concise way to represent a functional
interface instance. Syntax:
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
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
3
num >
20)
12 . collect ( Collectors . toList
13
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
4
3
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
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
Key Advantages
• Improves readability and maintainability.
Best Practices
• Use lambda expressions and streams judiciously to maintain readabil-
ity.
6
Further Reading
• Official Java Documentation: https://docs.oracle.com/javase/8/docs/api/