Lambda_Stream
Lambda_Stream
Functional programming in Java is based on lambda expressions, functional interfaces, and the
Stream API. Here are some important questions with answers:
• Pure Functions: Functions with no side effects and always return the same result for the
same inputs.
• Higher-Order Functions: Functions that accept other functions as arguments or return
functions.
• Immutability: Avoid modifying state or mutable data.
• Declarative Style: Code expresses "what to do" rather than "how to do it."
• Streams & Lazy Evaluation: Operations are performed on sequences in a pipeline.
• A functional interface is an interface with only one abstract method, used for lambda
expressions and method references.
• Examples:
◦ Runnable (with run() method)
◦ Callable (with call() method)
◦ Comparator<T> (with compare() method)
◦ Function<T, R> (with apply() method)
◦ Predicate<T> (with test() method)
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
}
Lambda expression is an anonymous function that allows writing concise code without needing
separate class implementations
• Syntax: java
ClassName::methodName
•
class Example {
• static void printMessage() {
• System.out.println("Method Reference Example");
• }
• }
•
• public class Main {
• public static void main(String[] args) {
• Runnable ref = Example::printMessage;
• ref.run();
• }
• }
•
// reduce()
int sum = numbers.stream().reduce(0, Integer::sum);
System.out.println(sum); // 15
// collect()
List<Integer> squaredNumbers = numbers.stream().map(n -> n *
n).collect(Collectors.toList());
System.out.println(squaredNumbers);
// forEach()
numbers.stream().forEach(System.out::println);
9. What are the differences between Parallel Streams and Sequential Streams?
• Methods in Optional:
◦ isPresent()
◦ orElse()
◦ orElseGet()
◦ orElseThrow()
◦ map()
◦ flatMap()
System.out.println(square.apply(5)); // 25
print.accept("Hello"); // Hello
System.out.println(randomValue.get()); // Random value
System.out.println(isEven.test(10)); // true