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