ในบทความนี้ เราจะเข้าใจวิธีการวนซ้ำบน ArrayList โดยใช้นิพจน์แลมบ์ดา คลาส ArrayList เป็นอาร์เรย์ที่ปรับขนาดได้ ซึ่งสามารถพบได้ในแพ็คเกจ java.util ความแตกต่างระหว่างอาร์เรย์ในตัวและ ArrayList ใน Java คือขนาดของอาร์เรย์ไม่สามารถแก้ไขได้
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
Run the program
ผลลัพธ์ที่ต้องการจะเป็น −
The list is defined as: Java Python Scala Mysql Redshift
อัลกอริทึม
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create an ArrayList, and iterate over it, and display it. Step 5 - In the ArrayList, add elements using the ‘add’ method. Step 6 - Display this on the console. Step 7 - Use the ‘forEach’ loop to iterate over the elements, and display them. Step 8 - Stop
ตัวอย่างที่ 1
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
import java.util.ArrayList;
public class Demo {
public static void print(ArrayList<String> input_list) {
System.out.print("\nThe list is defined as:\n ");
for(String language : input_list) {
System.out.print(language + " ");
}
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
ArrayList<String> input_list = new ArrayList<>();
input_list.add("Java");
input_list.add("Python");
input_list.add("Scala");
input_list.add("Mysql");
input_list.add("Redshift");
print(input_list);
}
} ผลลัพธ์
The required packages have been imported The list is defined as: Java Python Scala Mysql Redshift
ตัวอย่างที่ 2
ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ
import java.util.ArrayList;
public class Demo {
public static void print(ArrayList<Integer> input_list) {
System.out.print("\nThe list is defined as:\n ");
for(Integer elements : input_list) {
System.out.print(elements + " ");
}
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
ArrayList<Integer> input_list = new ArrayList<>();
input_list.add(500);
input_list.add(600);
input_list.add(700);
input_list.add(800);
input_list.add(950);
print(input_list);
}
} ผลลัพธ์
The required packages have been imported The list is defined as: 500 600 700 800 950