이 기사에서는 HashMap을 반복하는 방법을 이해할 것입니다. Java HashMap은 Java Map 인터페이스의 해시 테이블 기반 구현입니다. 키-값 쌍의 모음입니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Input Hashmap: {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,
알고리즘
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create a hashmap of strings and initialize elements in it using the ‘put’ method. Step 5 - Display the hashmap on the console. Step 6 - Iterate over the elements of the hashmap, and fetch each key using ‘keySet’ method. Step 7 - Display this on the console. Step 6 - Stop
예시 1
여기에서 모든 작업을 '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<String, String> 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(", ");
}
}
} 출력
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, 예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
import java.util.HashMap;
class Demo {
static void print_keys(HashMap<String, String> 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<String, String> 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<String, String> 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);
}
} 출력
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,