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,
廣告