Trong bài viết này, chúng ta sẽ hiểu cách tìm sublist trong List. List là collection có thứ tự cho phép lưu trữ và truy cập phần tử theo trình tự. Nó chứa các phương thức dựa trên chỉ số để chèn, cập nhật, xóa và tìm kiếm. Nó cũng có thể chứa phần tử trùng lặp. Một phần hoặc tập con của list được gọi là sublist.
Minh họa dưới đây:
Giả sử đầu vào là:
Input list: [101, 102, 103, 104, 105, 106, 107, 108, 109] Start Index: 3 End input: 6
Đầu ra mong muốn:
The Elements from 3 index position to 6 index position are: [104, 105, 106]
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo list integer input_list Bước 3 - Định nghĩa giá trị Bước 4 - Dùng hàm subList(3,6) tạo sublist giữa index 3 và 6 Bước 5 - Hiển thị kết quả Bước 6 - DỪNG
Ví dụ 1
Gom thao tác dưới 'main'.
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 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));
}
}
Kết quả
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]
Ví dụ 2
Đóng gói thao tác vào hàm thể hiện lập trình hướng đối tượng.
import java.util.LinkedList;
import java.util.List;
public class Demo {
static void sublist(List 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 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);
}
}
Kết quả
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]