Trong bài viết này, chúng ta sẽ hiểu cách duyệt qua một HashMap. Java HashMap là triển khai bảng băm của interface Map trong Java. Nó là tập hợp các cặp key-value.
Minh họa dưới đây:
Giả sử đầu vào là:
Input Hashmap: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI}
Đầu ra mong muốn:
The keys of the Hashmap are: Java, JavaScript, Mysql, Python, The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,
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 HashMap String, khởi tạo phần tử bằng 'put' Bước 5 - Hiển thị HashMap Bước 6 - Duyệt qua phần tử HashMap, lấy key bằng 'keySet' Bước 7 - Hiển thị trên console Bước 8 - DỪNG
Ví dụ 1
Gom thao tác dưới 'main'.
import java.util.HashMap;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap input_map = new HashMap<>();
input_map.put("Java", "Enterprise");
input_map.put("Python", "ML/AI");
input_map.put("JavaScript", "Frontend");
input_map.put("Mysql", "Backend");
System.out.println("The HashMap is defined as: " + input_map);
System.out.print("\nThe keys of the Hashmap are: ");
for(String key: input_map.keySet()) {
System.out.print(key);
System.out.print(", ");
}
System.out.print("\nThe Values of the Hashmap are: ");
for(String value: input_map.values()) {
System.out.print(value);
System.out.print(", ");
}
}
}
Kết quả
The required packages have been imported
The HashMap is defined as: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI}
The keys of the Hashmap are: Java, JavaScript, Mysql, Python,
The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,
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.HashMap;
class Demo {
static void print_keys(HashMap input_map){
System.out.print("\nThe keys of the Hashmap are: ");
for(String key: input_map.keySet()) {
System.out.print(key);
System.out.print(", ");
}
}
static void print_values(HashMap input_map){
System.out.print("\nThe Values of the Hashmap are: ");
for(String value: input_map.values()) {
System.out.print(value);
System.out.print(", ");
}
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap input_map = new HashMap<>();
input_map.put("Java", "Enterprise");
input_map.put("Python", "ML/AI");
input_map.put("JavaScript", "Frontend");
input_map.put("Mysql", "Backend");
System.out.println("The HashMap is defined as: " + input_map);
print_keys(input_map);
print_values(input_map);
}
}
Kết quả
The required packages have been imported
The HashMap is defined as: {Java=Enterprise, JavaScript=Frontend, Mysql=Backend, Python=ML/AI}
The keys of the Hashmap are: Java, JavaScript, Mysql, Python,
The Values of the Hashmap are: Enterprise, Frontend, Backend, ML/AI,