示例1:将lambda表达式定义为方法参数
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList languages = new ArrayList<>();
// add elements to the ArrayList
languages.add("java");
languages.add("swift");
languages.add("python");
System.out.println("ArrayList: " + languages);
// pass lambda expression as parameter to replaceAll() method
languages.replaceAll(e -> e.toUpperCase());
System.out.println("Updated ArrayList: " + languages);
}
}
输出
ArrayList: [java, swift, python]
Updated ArrayList: [JAVA, SWIFT, PYTHON]
在上面的示例中,我们创建了一个名为language的数组列表。注意这一行,
languages.replaceAll(e -> e.toUpperCase());
在这里, e -> e.toUpperCase()
是lambda表达式。它接受arraylist的所有元素,并将它们转换为大写。
示例2:将多行lambda主体作为函数参数传递
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList languages = new ArrayList<>(Arrays.asList("java", "python"));
System.out.println("ArrayList: " + languages);
// call the foEach() method
// pass lambda as argument fo forEach()
// reverse each element of ArrayList
System.out.print("Reversed ArrayList: ");
languages.forEach((e) -> {
// body of lambda expression
String result = "";
for (int i = e.length()-1; i >= 0 ; i--)
result += e.charAt(i);
System.out.print(result + ", ");
});
}
}
输出
ArrayList: [java, python]
Reversed ArrayList: avaj, nohtyp,
在上面的示例中,我们创建了arraylist 语言 。注意这一行,
languages.forEach((e) -> {
// body of lambda expression
String result = "";
for (int i = e.length()-1; i >= 0 ; i--)
result += e.charAt(i);
System.out.print(result + ", ");
});
在这里,我们将lambda表达式作为参数传递给ArrayList forEach()方法。 lambda表达式将反转arraylist的每个元素。