Java Functional Programming

Java functional programming got introduced as part of Java8.

This tutorial is to provide over all idea on functional programming and how stream, filter and mapping works.

Example

Below is the example to print numbers using for loop.

OUTPUT:

12345678

Above numbers can also be print with the help of streams in place of for loop as shown below highlighted in red.

As part of functional programming replace for loop with below highlighted line red in color.

numbers.stream() will covert list to stream.

OUTPUT:

12345678

Replace Practice::printNumber with System.out::println to print all numbers one by one. Now, we don’t require printNumber() function anymore as shown below.

OUTPUT:

12345678

Now, lets try to filter even numbers using structural programming with the help of isEven() functions as shown below:

OUTPUT:

2468

Filter

lets replace isEven() function with lambda expression and print all numbers.
.filter(n-> n % 2 == 0)

Visit URL to read more about lambda expression.

OUTPUT:

2468

Mapping

map in stream helps us to perform various operations on filtered stream. In below example, we are calculating the square of all even numbers.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

πŸ“ Blogs

πŸ“§ Imran Khan