Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java_Interview_QA

The document discusses lambda expressions in Java, introduced in Java 8, as a concise way to represent function interfaces, contrasting them with anonymous classes. It highlights the advantages of lambda expressions in terms of readability and reduced boilerplate code. An example is provided to demonstrate how to sort a list of strings in reverse order using a lambda expression.

Uploaded by

Sapna Madhavai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java_Interview_QA

The document discusses lambda expressions in Java, introduced in Java 8, as a concise way to represent function interfaces, contrasting them with anonymous classes. It highlights the advantages of lambda expressions in terms of readability and reduced boilerplate code. An example is provided to demonstrate how to sort a list of strings in reverse order using a lambda expression.

Uploaded by

Sapna Madhavai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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.

You might also like