Java - Functional Programming


// Functional Programming and Lambda in Java

// In functional programming, we avoid changing state (avoid multi-threading issues)

// Functional Programming is a programming paradigm, a style of building structure
// and elements of computer programs that treats computation as the evaluation of
// mathematical functions and avoids changing state and mutable data.

List <Integer> numbers = Arrays.asList(1, 3, 4, 6, 2, 7);
int sum = // Create a stream
            .filter(number -> (number % 2 != 0)) // Intermediate operation
            .reduce(0, Integer::sum); // Terminal operation

number -> (number % 2 != 0) // This is a Lambda expression
Integer::sum // This is a method reference

Lambda in Java use the concept of stream, a lot of intermediate operation
and one terminal operation.

static boolean isOdd(int number) {
  return number % 2 != 0;
} String[] {"Ram", "Robert", "Rahim"})
  .filter(s -> s.startsWith("Ro"))

s -> s.startsWith("Ro") is a function (also known as a Lambda expression).  This
function takes an input parameter name s and return true if it start with "Ro".

.map(String::toLowerCase) is the same as .map(s -> String.toLowerCase(s))

String::toLowerCase is a method reference

.map mean mapping from the old value to new value.  We can also expand the value into
multiple values.

Intermediate operation returns a new stream.

map, filter, distinct, sorted
reduce, collect;
List<Integer> oddNumbers =;

A Lambda expression is an anonymous function.  It is a method without declaration.  There will
be no access modifier, no return value declaration, and no name.  It is a shorthand that allows
you to write a method in the same place you are going to use it.  It is especially useful when
a method is being used only once, and the method definition is short.  Syntax: 
Parameters -> Executed Code

// Example Lambda expressions:
(number) -> (number % 2 != 0)

// Relationship between Lambda expression and Functional Interfaces
@FunctionalInterface is an interface that has only one method declared.

A Predicate takes a value and return a boolean
A Consumer takes an object and return void
A Function takes an object and return some other object
A BiFunction takes two objects and return other object
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License