이 기사에서는 해시 맵의 요소를 반복하는 방법을 이해할 것입니다. Java HashMap은 Java Map 인터페이스의 해시 테이블 기반 구현입니다. 키-값 쌍의 모음입니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Run the program
원하는 출력은 -
The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript
알고리즘
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
예시 1
여기에서 모든 작업을 '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());
}
}
} 출력
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
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);
}
} 출력
Required packages have been imported A Hashmap is declared The elements of the HashMap are: 1 : Java 2 : Python 3 : Scala 4 : Javascript