Java Interview Questions and Answers
# Java Interview Questions and Answers
## Lambda Expressions
### 1. What is a lambda expression in Java, and how is it different from an
anonymous class?
A lambda expression is a concise way to represent a function interface (an
interface with a single abstract method) using a block of code. Lambda
expressions were introduced in Java 8 and help reduce boilerplate code in
scenarios like iterating collections or implementing event listeners.
Anonymous classes, on the other hand, allow you to define and instantiate a
class at the same time. While both can be used to provide behavior, lambda
expressions are more readable and compact, as they do not require the
creation of a class.
Example:
- Anonymous Class:
```java
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Running");
}
};
```
- Lambda Expression:
```java
Runnable r = () -> System.out.println("Running");
```
### 2. Write a lambda expression to sort a list of strings in reverse order.
```java
import java.util.*;
public class LambdaExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("Apple", "Orange", "Banana", "Grapes");
// Sorting in reverse order using Lambda Expression
list.sort((s1, s2) -> s2.compareTo(s1));
// Printing the sorted list
list.forEach(System.out::println);
```
---
The above demonstrates lambda expressions' use in real-world scenarios for
better clarity.