ในบทความนี้ เราจะทำความเข้าใจวิธีค้นหารายการย่อยในรายการ รายการคือคอลเลกชันที่ได้รับคำสั่งซึ่งช่วยให้เราจัดเก็บและเข้าถึงองค์ประกอบตามลำดับได้ ประกอบด้วยวิธีการที่อิงดัชนีเพื่อแทรก อัปเดต ลบและค้นหาองค์ประกอบ นอกจากนี้ยังสามารถมีองค์ประกอบที่ซ้ำกัน ส่วนหรือส่วนย่อยของรายการเรียกว่ารายการย่อย
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
Input list: [101, 102, 103, 104, 105, 106, 107, 108, 109] Start Index: 3 End input: 6
ผลลัพธ์ที่ต้องการจะเป็น −
The Elements from 3 index position to 6 index position are: [104, 105, 106]
อัลกอริทึม
Step 1 - START Step 2 - Declare an integer list namely input_list. Step 3 - Define the values. Step 4 - Use the function subList(3,6) to create a sublist between index value 3 and 6. Step 5 - Display the result Step 6 - Stop
ตัวอย่างที่ 1
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
import java.util.LinkedList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
int index_start=3;
int index_end=6;
List<Integer> input_list= new LinkedList<>();
for (int i=1; i<=9; i++){
input_list.add(i + 100);
}
System.out.println("The list is defined as: "+input_list);
input_list.subList(index_start,index_end);
System.out.println("The Elements from " +index_start + " index position to "+index_end +" index position are: "+input_list.subList(3,6));
}
} ผลลัพธ์
The list is defined as: [101, 102, 103, 104, 105, 106, 107, 108, 109] The Elements from 3 index position to 6 index position are: [104, 105, 106]
ตัวอย่างที่ 2
ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ
import java.util.LinkedList;
import java.util.List;
public class Demo {
static void sublist(List<Integer> input_list, int index_start, int index_end){
input_list.subList(index_start,index_end);
System.out.println("The Elements from " +index_start + " index position to "+index_end +" index position are: "+input_list.subList(3,6));
}
public static void main(String[] args) {
int index_start=3;
int index_end=6;
List<Integer> input_list= new LinkedList<>();
for (int i=1; i<=9; i++){
input_list.add(i + 100);
}
System.out.println("The list is defined as: "+input_list);
sublist(input_list, index_start, index_end);
}
} ผลลัพธ์
The list is defined as: [101, 102, 103, 104, 105, 106, 107, 108, 109] The Elements from 3 index position to 6 index position are: [104, 105, 106]