Trong bài này, chúng ta sẽ hiểu cách lặp qua các phần tử của hash-map. Java HashMap là cách triển khai dựa trên bảng băm của giao diện Bản đồ của Java. Nó là một tập hợp các cặp khóa-giá trị.
Dưới đây là một minh chứng về điều tương tự -
Giả sử đầu vào của chúng tôi là -
Run the program
Đầu ra mong muốn sẽ là -
The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript
Thuật toán
Step 1 - START Step 2 - Declare a HashMap namely input_map. Step 3 - Define the values. Step 4 - Iterate using a for-loop, use the getKey() and getValue() functions to fetch the key and value associated to the index. Step 5 - Display the result Step 6 - Stop
Ví dụ 1
Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "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<String, String> input_map = new HashMap<String, String>();
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<String, String> set : input_map.entrySet()) {
System.out.println(set.getKey() + " : " + set.getValue());
}
}
} Đầu ra
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
Ở đây, chúng tôi đóng gói các hoạt động thành các hàm trưng bày lập trình hướng đối tượng.
import java.util.HashMap;
import java.util.Map;
public class Demo {
static void print(Map<String, String> input_map){
System.out.println("The elements of the HashMap are: ");
for (Map.Entry<String, String> 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<String, String> input_map = new HashMap<String, String>();
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);
}
} Đầu ra
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript