Java 程序如何将 lambda 表达式作为方法参数传递
在本文中,我们将了解如何将 lambda 表达式作为方法参数传递。Lambda 表达式是接受参数并返回一个值的一个简短代码块。
以下是相同方法的演示 −
输入
假设我们的输入为 −
("Apple", "Orange", "Grapes")输出
所需的输出为 −
elppA, egnarO, separG
算法
Step 1 - START Step 2 - We import the required packages. Step 3 - In the main function, we define an ‘ArrayList’ of data. Step 4 - This is displayed on the console. Step 5 - Now, a ‘forEach’ loop is used to iterate over the elements of the ArrayList from the end, instead of the beginning. Step 6 - The element at every index is accessed and incremented by a specific value. Step 7 - This will result in the ArrayList elements being displayed in reverse order.
示例 1
这里,整数已预定义,其值在控制台上访问并显示出来。
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<String> Fruits = new ArrayList<>(Arrays.asList("Apple", "Orange", "Grapes"));
System.out.println("The ArrayList is defined as : " + Fruits);
System.out.print("The Reversed ArrayList is: ");
Fruits.forEach((e) -> {
String result = "";
for (int i = e.length()-1; i >= 0 ; i--)
result += e.charAt(i);
System.out.print(result + ", ");
});
}
}输出
The ArrayList is defined as : [Apple, Orange, Grapes] The Reversed ArrayList is: elppA, egnarO, separG,
示例 2
这里,整数已预定义,其值在控制台上访问并显示出来。
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<String> Games = new ArrayList<>(Arrays.asList("Football", "Cricket", "Baseball"));
System.out.println("The ArrayList is defined as : " + Games );
System.out.print("The Reversed ArrayList is: ");
Games .forEach((e) -> {
String result = "";
for (int i = e.length()-1; i >= 0 ; i--)
result += e.charAt(i);
System.out.print(result + ", ");
});
}
}输出
The ArrayList is defined as : [Football, Cricket, Baseball] The Reversed ArrayList is: llabtooF, tekcirC, llabesaB,
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP