Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
Now Reading
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Functional programming in Java deals with using pure functions, immutability, and higher-order functions. It is an important concept in Java, and here is a tutorial for learners to master it quickly.
This tutorial deals with basic concepts such as functional programming in Java: how functional techniques improve your Java programs, the differences between functional and purely functional programming, why functional programming matters, and much more.
Functional programming in Java is a programming paradigm that emphasizes using higher-order functions, immutability, and pure functions. It introduces features like lambda expressions and the Stream API to support functional-style programming. This approach promotes code readability, modularity, and reusability while enabling better parallel and concurrent programming.
In Java, functional programming can be implemented using features introduced in Java 8 and subsequent versions. Here's how you can implement functional programming in Java:
Syntax: (parameter list) -> { function body }
Syntax: @FunctionalInterface
interface MyFunctionalInterface {
void performAction();
}
Syntax: stream()
.filter(predicate)
.map(mapper)
.reduce(identity, accumulator)
Now, let us explore some of the core concepts of functional programming.
In Java, higher-order functions can be implemented using functional interfaces. A higher-order function takes one or more functions as arguments and/or returns a function.
Example:
In this example, we have two functions: square and increment. The square function squares a given number, and the increment function increments a given number by 1.
The compose function is a higher-order function that takes two functions as arguments and returns a new function. In this case, we use the compose() method provided by the Function functional interface to compose the square and increment functions.
The composed function first applies the increment function to the input and then the square function to the result. This means that the square function is applied to the result of the increment function.
In the main() method, we create the square and increment functions using lambda expressions. Then, we compose these functions using the compose() method to create the compose function. Finally, we apply the compose function to the number 5 using the apply() method, resulting in 36.
import java.util.function.Function;
public class main {
public static void main(String[] args) {
Function<Integer, Integer> square = num -> num * num;
Function<Integer, Integer> increment = num -> num + 1;
Function<Integer, Integer> compose = square.compose(increment);
int result = compose.apply(5); // Output: 36
System.out.println("Result: " + result);
}
}
A pure function is a function that always produces the same output for the same input and has no side effects. It does not modify any external state or rely on mutable data.
Example:
In this example, the multiply() function is pure. It takes two integers as input, multiplies them, and returns the result.
When we call the multiply() function with the same input values (5 and 3), it will always return the same output (15). The function has no side effects, such as modifying global variables or printing to the console.
public class PureFunctionExample {
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
int result = multiply(5, 3); // Output: 15
System.out.println("Result: " + result);
}
}
Lambda expressions in Java allow you to define and use anonymous functions concisely.
Example:
In this example, we first import the necessary classes (ArrayList, List, Consumer) and define a class called main. Then, in the main() method, we create an ArrayList called names and add some strings. We use the forEach() method on the names list to iterate over each element.
We can then define a functional interface called Calculator with a single abstract method calculate(). A lambda expression (a, b) -> a + b implements the calculate() method, adding two integers and returning the sum. We then create an instance of the Calculator functional interface using the lambda expression and calculate the sum of 5 and 3.
A Consumer functional interface is then defined with a single abstract method accept().
The lambda expression str -> System.out.println(str.toUpperCase()) implements the accept() method, printing the uppercase version of the given string.
We create an instance of the Consumer functional interface using the lambda expression and call the accept() method with the string "hello", which prints "HELLO" to the console. Finally, we define the Calculator functional interface with a single abstract method calculate() that takes two integers and returns an integer.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("John");
names.add("Jane");
names.add("Alice");
// Example 1: Using a lambda expression as a parameter
names.forEach(name -> System.out.println("Hello, " + name));
// Example 2: Using a lambda expression with multiple parameters
Calculator add = (a, b) -> a + b;
int sum = add.calculate(5, 3);
System.out.println("Sum: " + sum);
// Example 3: Using a lambda expression as a variable
Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase());
printUpperCase.accept("hello");
}
interface Calculator {
int calculate(int a, int b);
}
}
Imperative programming is a programming paradigm where programs are structured around the concept of state and instructions that change that state. In imperative programming, you explicitly specify the sequence of steps to be executed to achieve a desired result.
Example:
public class ImperativeProgrammingExample {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
sum += numbers[i];
}
}
System.out.println("Sum of even numbers: " + sum);
}
}
Declarative programming is a programming paradigm where programs describe the desired results or outcomes without specifying the step-by-step procedure to achieve those results. In declarative programming, you focus on what you want to accomplish rather than how.
Example:
import java.util.Arrays;
public class DeclarativeProgrammingExample {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.sum();
System.out.println("Sum of even numbers: " + sum);
}
}
Here are some functional programming techniques:
In Java, a function is represented by a method. A method is a block of code that performs a specific task and can be invoked or called from other parts of the program.
Example:
public class main {
public static void main(String[] args) {
// Calling the function
int sum = addNumbers(5, 3);
System.out.println("Sum: " + sum);
}
// Function to add two numbers and return the result
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
}
Function composition is a technique in functional programming where you combine multiple functions to create a new function. The output of one function becomes the input for the next function, forming a chain of operations.
Example:
import java.util.function.Function;
public class main {
public static void main(String[] args) {
// Define two functions: addOne and multiplyByTwo
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> multiplyByTwo = x -> x * 2;
// Compose the functions
Function<Integer, Integer> composedFunction = addOne.andThen(multiplyByTwo);
// Apply the composed function to an input
int result = composedFunction.apply(5);
System.out.println("Result: " + result); // Output: 12
}
}
Monads are a programming concept commonly used in functional programming to manage and encapsulate computations with additional context. While Java doesn't have built-in support for monads, we can still implement monad-like behavior using libraries like Vavr or custom code.
First, we must the Vavr dependency to your project. We can use a build tool like Maven for managing dependencies. In the case of Maven, we must add the following dependency to our pom.xml file:
We can then import the necessary Vavr classes in our code in this manner:
Finally, we can run the below code with the Vavr library:
Currying is a technique in functional programming where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument.
Example:
import java.util.function.Function;
public class main {
public static void main(String[] args) {
// Currying a two-argument function
Function<Integer, Function<Integer, Integer>> curriedAdd = a -> b -> a + b;
// Partially apply the first argument
Function<Integer, Integer> add5 = curriedAdd.apply(5);
// Call the curried function with the remaining argument
int result = add5.apply(3);
System.out.println("Result: " + result); // Output: 8
}
}
Recursion in Java is a programming technique where a method can call itself for solving problems by breaking them down into similar but smaller subproblems. In a recursive function, the function repeatedly calls itself with modified inputs until a base case is reached, which defines the terminating condition for the recursion.
Example:
public class main {
public static void main(String[] args) {
int number = 5;
int factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}
public static int calculateFactorial(int n) {
if (n == 0) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
There are many advantages of Functional Programming. Some of them are:
This tutorial will be beneficial for students keen on mastering functional programming in Java. Since it is one of the most important concepts of Java, one must carefully go through tutorials and learning materials to grasp such concepts. One could also enroll in online learning platforms such as upGrad to learn more about these concepts from industry experts with the help of specially tailored courses.
1. What are lambda expressions in functional programming?
Lambda expressions are anonymous functions that allow you to define functionality inline concisely. They are a key feature of functional programming in Java.
2. Is functional programming suitable for all types of Java projects?
Functional programming can be beneficial in various Java projects, especially those that involve processing collections, parallel execution, or complex data transformations.
3. Are there any frameworks or libraries that support functional programming in Java?
Yes, several libraries and frameworks in the Java ecosystem support functional programming. Some popular ones include Google Guava and Java 8's Stream API itself. These libraries provide additional functional programming features and utilities to enhance your Java code.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...