Hashset
Duy Văn | 12/03/2025
HashSet về cơ bản tương tự như Set ở phía Python, chỉ cho phép các giá trị không trùng lặp, nó hoạt động theo dạng nếu như bạn thêm một phần tử đã tồn tại thì nó sẽ không xuất hiện thêm vào nữa
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
}
}
Thêm phần tử vào HashSet
Để thêm phần tử vào HashSet, chúng ta sử dụng method add()
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("BMW");
System.out.println(cars);
}
}
Kết quả sẽ là ["Volvo", "BMW", "Ford"] vì nó đã loại bỏ phần tử “BMW” thứ 2
Kiểm tra phần tử có trong HashSet
Để kiểm tra xem một phần tử có trong HashSet hay không, chúng ta sử dụng method contains()
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");;
System.out.println(car.contains("Volvo"));
}
}
Xóa phần tử trong HashSet
Để xóa phần tử trong HashSet, chúng ta sử dụng method remove()
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.remove("BMW");
System.out.println(cars);
}
}
Hoặc xoá hết bằng method clear()
Độ dài của HashSet
Để lấy độ dài của HashSet, chúng ta sử dụng method size()
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println(cars.size());
}
}
Loop qua HashSet
Để loop qua HashSet thì chúng ta cần sử dụng for-each
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
for (String i : cars) {
System.out.println(i);
}
}
}
Lý do là vì chúng ta sẽ không thể truy cập vào phần tử thông qua index, vì nó đã hash rồi
HashSet với các kiểu dữ liệu khác nhau
HashSet cũng có thể chứa các kiểu dữ liệu khác nhau
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<Integer>();
numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
System.out.println(numbers);
HashSet<Boolean> booleans = new HashSet<Boolean>();
booleans.add(true);
booleans.add(false);
System.out.println(booleans);
}
}