Trong bài viết này, chúng ta sẽ hiểu cách duyệt qua các phần tử của 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à:
Run the program
Đầu ra mong muốn:
The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo HashMap input_map Bước 3 - Định nghĩa giá trị Bước 4 - Duyệt bằng for-loop, dùng getKey() và getValue() lấy key và value theo index 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.HashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args){
System.out.println("Required packages have been imported");
Map input_map = new HashMap();
input_map.put("1", "Java");
input_map.put("2", "Python");
input_map.put("3", "Scala");
input_map.put("4", "Javascript");
System.out.println("A Hashmap is declared\n");
System.out.println("The elements of the HashMap are: ");
for (Map.Entry set : input_map.entrySet()) {
System.out.println(set.getKey() + " : " + set.getValue());
}
}
}
Kết quả
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript
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;
import java.util.Map;
public class Demo {
static void print(Map input_map){
System.out.println("The elements of the HashMap are: ");
for (Map.Entry set : input_map.entrySet()) {
System.out.println(set.getKey() + " : " + set.getValue());
}
}
public static void main(String[] args){
System.out.println("Required packages have been imported");
Map input_map = new HashMap();
input_map.put("1", "Java");
input_map.put("2", "Python");
input_map.put("3", "Scala");
input_map.put("4", "Javascript");
System.out.println("A Hashmap is declared\n");
print(input_map);
}
}
Kết quả
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript