[go: up one dir, main page]

0% found this document useful (0 votes)
18 views5 pages

Lambda_Stream

The document provides an overview of functional programming in Java, highlighting key concepts such as lambda expressions, functional interfaces, and the Stream API. It includes essential questions and answers regarding the features, differences between various functional programming components, and examples of their usage. Additionally, it explains the purpose of Optional and the distinctions between Function, Consumer, Supplier, and Predicate interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Lambda_Stream

The document provides an overview of functional programming in Java, highlighting key concepts such as lambda expressions, functional interfaces, and the Stream API. It includes essential questions and answers regarding the features, differences between various functional programming components, and examples of their usage. Additionally, it explains the purpose of Optional and the distinctions between Function, Consumer, Supplier, and Predicate interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Functional Programming in Java - Questions & Answers

Functional programming in Java is based on lambda expressions, functional interfaces, and the
Stream API. Here are some important questions with answers:

1. What is Functional Programming in Java?

• Functional programming is a paradigm where functions are treated as rst-class citizens,


allowing them to be passed as arguments, returned from other functions, and assigned to
variables. It focuses on immutability and declarative programming.

2. What are the key features of functional programming in Java?

• 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.

3. What is a Functional Interface in Java?

• 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();
}

4. What are Lambda Expressions in Java?

Lambda expression is an anonymous function that allows writing concise code without needing
separate class implementations
• Syntax: java

(parameters) -> { body }


fi
MyFunctionalInterface func = () -> System.out.println("Hello
Functional Programming!”);
func.execute();

5. What is Method Reference in Java?

• A shorthand for lambda expressions where a method is directly referenced.


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();
• }
• }

6. What is the Stream API in Java?

• The Stream API provides functional programming features to process collections.


List<String> names = Arrays.asList("John", "Jane",


"Jack");
• names.stream()
• .filter(name -> name.startsWith("J"))
• .forEach(System.out::println);

• Operations in Stream API:


◦ Intermediate Operations: filter(), map(), sorted(), distinct()
◦ Terminal Operations: collect(), forEach(), count(), reduce()

7. What is the difference between map() and flatMap() in Java Streams?

Featu map() flatMap()


re
Input Single value Collection or Stream
Type
Outpu
Stream of Streams Flattened Stream
t Type
Exam List<String> List<List<String>>
ple names.map(String::toUppe nestedList.flatMap(Collection::
rCase) stream)
Example:

List<String> words = Arrays.asList("Hello", "World");


List<Character> chars = words.stream()
.flatMap(word ->
word.chars().mapToObj(c -> (char) c))
.collect(Collectors.toList());

8. What is the difference between reduce(), collect(), and forEach()


in Java Streams?

• reduce(): Used to perform aggregation like sum, min, max.


• collect(): Used to transform a stream into a collection.
• forEach(): Used for iteration.
Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// 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?

Feature Sequential Stream Parallel Stream


Execution Single-threaded Multi-threaded
Performanc Slower for large
Faster for large datasets
e datasets
Order Maintains order May not maintain order
parallelStream(
Example stream()
)

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);


numbers.parallelStream().forEach(System.out::println);

10. What are Optional and its bene ts in Java?

• Optional is used to handle null values safely and avoid NullPointerException.


Optional<String> optionalValue = Optional.ofNullable(null);
• System.out.println(optionalValue.orElse("Default
Value"));

• Methods in Optional:
◦ isPresent()
◦ orElse()
◦ orElseGet()
◦ orElseThrow()
◦ map()
◦ flatMap()

11. What is the difference between Function, Consumer, Supplier, and


Predicate?

Interface Method Description


Function<T,
apply(T t) Takes input and returns output
R>
accept(T
Consumer<T> Takes input but returns nothing
t)
Returns a value but takes no
Supplier<T> get() input
Predicate<T> test(T t) Returns a boolean value
fi
Example:

Function<Integer, Integer> square = x -> x * x;


Consumer<String> print = System.out::println;
Supplier<Double> randomValue = Math::random;
Predicate<Integer> isEven = x -> x % 2 == 0;

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

You might also like