Real-World Use Cases and Examples
Examples of Lambda Usage in Real Projects:
Web Development:
Routing in Web Frameworks: Lambda expressions are often used in web frameworks like Spring Boot for defining routes and handling HTTP requests.
// Spring Web Example @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } }
Data Processing:
Batch Processing: Lambdas are utilized in batch processing applications for filtering, mapping, and reducing large datasets efficiently.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println); // Output: Alice
Concurrency and Parallelism:
Parallel Stream Processing: Lambda expressions enable parallel processing of collections, leveraging multi-core processors.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum(); System.out.println("Sum: " + sum); // Output: Sum: 55
Case Studies and Problem Solving with Lambdas:
Problem: Computing Average Age:
Description: Given a list of people, compute the average age of all adults (age >= 18) using lambda expressions.
class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } } public class AverageAgeExample { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", 25), new Person("Bob", 17), new Person("Charlie", 30) ); double averageAge = people.stream() .filter(person -> person.getAge() >= 18) .mapToInt(Person::getAge) .average() .orElse(0.0); System.out.println("Average Age of Adults: " + averageAge); // Output: Average Age of Adults: 27.5 } }
Problem: Finding Longest Word:
Description: Given a list of words, find and print the longest word using lambda expressions.
import java.util.Arrays; import java.util.List; public class LongestWordExample { public static void main(String[] args) { List<String> words = Arrays.asList("apple", "banana", "orange", "kiwi"); String longestWord = words.stream() .max((word1, word2) -> word1.length() - word2.length()) .orElse(""); System.out.println("Longest Word: " + longestWord); // Output: Longest Word: banana } }
These examples demonstrate real-world applications of lambda expressions in various domains, including web development, data processing, concurrency, and problem-solving scenarios. By leveraging the concise syntax and functional programming capabilities of lambdas, developers can write expressive and efficient code for a wide range of tasks.
Last updated