This video introduces the concept of lambda expressions in Java and their relationship to functional programming concepts.
A functional interface in Java is an interface that contains exactly one abstract method. Lambda expressions provide a way to implement these interfaces concisely.
Here's an example of a functional interface and its implementation using lambda expression:
// Functional interface definition
@FunctionalInterface
interface StringProcessor {
String process(String input);
}
// Implementation using a lambda expression
StringProcessor reverser = (String s) -> {
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
};
// Usage
String result = reverser.process("Hello"); // Returns "olleH"
The key built-in functional interfaces in the java.util.function package include:
R apply(T t)
void accept(T t)
T get()
boolean test(T t)
In this video, you'll learn advanced techniques for using lambda expressions with the Stream API and other functional programming patterns in Java.
Method references provide an even more concise way to express lambda expressions that simply call an existing method.
There are four types of method references:
// 1. Reference to a static method
Function<String, Integer> parser = Integer::parseInt;
// 2. Reference to an instance method of a particular object
String str = "Hello";
Supplier<Integer> lengthSupplier = str::length;
// 3. Reference to an instance method of an arbitrary object of a particular type
Function<String, Integer> lengthFunc = String::length;
// 4. Reference to a constructor
Supplier<List<String>> listSupplier = ArrayList::new;
Java's Stream API works seamlessly with lambda expressions to process collections of objects:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
// Filter names starting with 'A'
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
// Transform names to uppercase
List<String> upperNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Find any name longer than 5 characters
Optional<String> longName = names.stream()
.filter(name -> name.length() > 5)
.findAny();
// Combine multiple operations
double averageLength = names.stream()
.filter(name -> name.length() > 3)
.mapToInt(String::length)
.average()
.orElse(0);