Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:30:59 Viewed : 578
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. While Java is primarily an object-oriented language, Java 8 and subsequent versions introduced features that bring functional programming concepts to the language. Here are some key functional programming concepts in Java:
First-Class Functions:
java// Example of passing a lambda expression as an argument
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println("Hello, " + name));
Higher-Order Functions:
java// Example of a higher-order function
Function<Integer, Integer> multiplyByTwo = x -> x * 2;
Function<Integer, Integer> addOne = x -> x + 1;
// Combining functions
Function<Integer, Integer> combined = multiplyByTwo.andThen(addOne);
int result = combined.apply(3); // Result: (3 * 2) + 1 = 7
Immutability:
final
keyword and the creation of immutable classes. Immutable objects cannot be modified after they are created.java// Example of an immutable class
public final class ImmutablePerson {
private final String name;
private final int age;
public ImmutablePerson(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods...
}
Pure Functions:
java// Example of a pure function
public int add(int a, int b) {
return a + b;
}
Referential Transparency:
java// Referential transparency example
int result1 = add(2, 3); // Result: 5
int result2 = add(2, 3); // Result: 5
// Since add is a pure function, result1 and result2 are guaranteed to be the same.
Lazy Evaluation:
java// Lazy evaluation with streams
List<String> words = Arrays.asList("apple", "banana", "orange");
List<String> filteredWords = words.stream()
.filter(s -> {
System.out.println("Filtering: " + s);
return s.length() > 5;
})
.limit(2)
.collect(Collectors.toList());
These functional programming concepts in Java provide developers with tools to write more expressive, modular, and maintainable code. While Java is not a purely functional language, these features allow developers to incorporate functional programming principles into their applications.