Trong bài viết này, chúng ta sẽ hiểu cách duyệt qua một Set. Set là Collection không chứa phần tử trùng lặp. Nó mô hình hóa trừu tượng tập hợp toán học. Interface Set chỉ chứa phương thức kế thừa từ Collection và thêm hạn chế cấm phần tử trùng lặp.
Minh họa dưới đây:
Giả sử đầu vào là:
Input set: [Java, Scala, Mysql, Python]
Đầu ra mong muốn:
Iterating over Set using for-each loop: Java, Scala, Mysql, Python
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo biến Bước 3 - Định nghĩa giá trị Bước 4 - Tạo HashSet, khởi tạo phần tử bằng 'add' Bước 5 - Hiển thị HashSet Bước 6 - Duyệt qua phần tử HashSet, lấy từng giá trị Bước 7 - Hiển thị trên console Bước 8 - DỪNG
Ví dụ 1
Gom thao tác dưới 'main'. Dùng for-each.
import java.util.Set;
import java.util.HashSet;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
Set input_set = new HashSet<>();
input_set.add("Java");
input_set.add("Scala");
input_set.add("Python");
input_set.add("Mysql");
System.out.println("The set is defined as: " + input_set);
System.out.println("\nIterating over Set using for-each loop:");
for(String elements : input_set) {
System.out.print(elements);
System.out.print(", ");
}
}
}
Kết quả
The required packages have been imported The set is defined as: [Java, Scala, Mysql, Python] Iterating over Set using for-each loop: Java, Scala, Mysql, Python,
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. Dùng Iterator.
import java.util.Set;
import java.util.HashSet;
public class Demo {
static void print_set(Set input_set){
System.out.println("\nIterating over Set using for-each loop:");
for(String elements : input_set) {
System.out.print(elements);
System.out.print(", ");
}
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
Set input_set = new HashSet<>();
input_set.add("Java");
input_set.add("Scala");
input_set.add("Python");
input_set.add("Mysql");
System.out.println("The set is defined as: " + input_set);
print_set(input_set);
}
}
Kết quả
The required packages have been imported The set is defined as: [Java, Scala, Mysql, Python] Iterating over Set using for-each loop: Java, Scala, Mysql, Python,