Exercise:
Write a Java Program to pass lambda expression as a method argument.
Click Here to View the Solution!
import java.util.ArrayList;
class lambda {
public static void main(String[] args) {
ArrayList<String> city =
new ArrayList<>();
// add elements to the ArrayList city
city.add(
"London");
city.add(
"New York");
city.add(
"Washington");
System.out.println(
"ArrayList: " + city);
// pass lambda expression as parameter
city.replaceAll(e -> e.toUpperCase());
System.out.println(
"Updated ArrayList: " + city);
}
}
Click Here to View the Output!
ArrayList: [London, New York, Washington] Updated ArrayList: [LONDON, NEW YORK, WASHINGTON]
Click Here to View the Explanation!
- In this program, firstly an arraylist called
city
is created. - Next, elements in lowercase letters are added to this arraylist by the arraylist method called
add()
. - After adding elements in the list, arraylist is displayed on the screen.
- Lastly, all the elements in the list are replaced by their uppercase versions using the lambda expression. Notice the expression below:
languages.replaceAll(e -> e.toUpperCase());
toUpperCase()
method takes a string and converts all of its letters into uppercase.