ในบทความนี้ เราจะเข้าใจวิธีการส่งผ่านนิพจน์แลมบ์ดาเป็นอาร์กิวเมนต์ของเมธอด นิพจน์แลมบ์ดาคือโค้ดสั้นๆ ที่รับพารามิเตอร์และส่งกลับค่า
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
("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,